0

I'm trying to make the condition that if the [0][0] entry in the array is not equal to 1 or 2 the program prints an error message. I can't get it to work, and I know it's because I can't get the logic correct.

try:
    with open(input_script) as input_key:
        for line in input_key.readlines():
            x=[item for item in line.split()]
            InputKey.append(x)
    if InputKey[0][0] == 1 or 2:     #This is where my condition is being tested.
        print '.inp file succesfully imported' #This is where my success (or fail) print comes out.
    else:
        print 'failed'
except IOError:
    print '.inp file import unsuccessful. Check that your file-path is valid.'                                
4

2 回答 2

2

您的if病情评估为:

if (InputKey[0][0] == 1) or 2: 

这相当于:

if (InputKey[0][0] == 1) or True: 

这将始终评估为True.


你应该使用:

if InputKey[0][0] == 1 or InputKey[0][0] == 2:

或者

if InputKey[0][0] in (1, 2):

请注意,如果您InputKey[0][0]是 type string,则可以将其转换为intusing int(InputType[0][0]),否则它将与1or不匹配2

除此之外,您的for循环可以修改为:

for line in input_key.readlines():         
    # You don't need list comprehension. `line.split()` itself gives a list
    InputKey.append(line.split())  
于 2013-07-21T07:35:30.877 回答
2

if InputKey[0][0] == 1 or 2:是相同的:

(InputKey[0][0] == 1) or (2)

并且2被认为是True( bool(2) is True),因此这个意志语句将始终为真。

您希望 python 将其解释为:

InputKey[0][0] == 1 or InputKey[0][0] == 2

甚至:

InputKey[0][0] in [1, 2]
于 2013-07-21T07:36:14.380 回答