0
Problem with the or statement
I wrote this code: num=7 if num == 5 or 9 or 11: print(num) else: print(invalid) I got the output: 7 How is this possible when num is neither 5, 9 nor 11. The or statement is true if one of the conditions is True, which is not the case in this example. Can someone explain this to me please.
6 Respostas
+ 2
This can be simplified to:
if num in (5, 9, 11)
+ 2
thanx for ya help friends!!
turns out i just had to repeat "num" before each value.
if num == 5 or num == 9 or num == 11:
than i got the right output. i tried with more examples and it works.
+ 1
Вазген Арутюнян This doesn't work.
+ 1
num == 5 evaluates to a False.....then...
False or 9 evaluates to True because any number other than 0 (zero) evals to True..
then it stops there...short circuit evaluation..so the result of the whole expression is True...and num (7) is printed.
This is what your looking to do:-
if num == 5 or num == 9 or num == 11
0
Ok, I'm sorry
0
Seb TheS
thanx, it makes it a lot easier when there are many elements in the statement