无法找到布尔逻辑来使其工作

时间:2013-07-21 07:34:42

标签: python if-statement boolean boolean-expression

我试图使条件是如果数组中的[0] [0]条目不等于1或2,程序将输出错误消息。我无法让它工作,我知道这是因为我无法使逻辑正确。

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.'                                

2 个答案:

答案 0 :(得分: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]类型为string,则可以使用int将其转换为int(InputType[0][0]),否则与1不匹配}或2

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

for line in input_key.readlines():         
    # You don't need list comprehension. `line.split()` itself gives a list
    InputKey.append(line.split())  

答案 1 :(得分:2)

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

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

2被视为Truebool(2) is True),因此此语句将始终为True。

您希望python将其解释为:

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

甚至:

InputKey[0][0] in [1, 2]
相关问题