Reputation: 3557
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.'
Upvotes: 0
Views: 88
Reputation: 213213
Your if
condition is evaluated as:
if (InputKey[0][0] == 1) or 2:
which is equivalent to:
if (InputKey[0][0] == 1) or True:
which will always evaluated to True
.
if InputKey[0][0] == 1 or InputKey[0][0] == 2:
or
if InputKey[0][0] in (1, 2):
Note that, if your InputKey[0][0]
is of type string
, you can convert it to int
using int(InputType[0][0])
, else it won't match with 1
or 2
.
Apart from that, your for
loop can be modified as:
for line in input_key.readlines():
# You don't need list comprehension. `line.split()` itself gives a list
InputKey.append(line.split())
Upvotes: 2
Reputation: 59974
if InputKey[0][0] == 1 or 2:
is the same as:
(InputKey[0][0] == 1) or (2)
And 2
is considered True
(bool(2) is True
), thus this will statement will always be True.
You want python to interpret this as:
InputKey[0][0] == 1 or InputKey[0][0] == 2
Or even:
InputKey[0][0] in [1, 2]
Upvotes: 2