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.

26th Jan 2020, 9:47 PM
Goran
6 Antworten
+ 2
This can be simplified to: if num in (5, 9, 11)
26th Jan 2020, 10:25 PM
Seb TheS
Seb TheS - avatar
+ 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.
26th Jan 2020, 10:07 PM
Goran
+ 1
26th Jan 2020, 10:03 PM
Seb TheS
Seb TheS - avatar
+ 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
26th Jan 2020, 10:13 PM
rodwynnejones
rodwynnejones - avatar
0
Ok, I'm sorry
26th Jan 2020, 10:06 PM
Вазген Арутюнян
Вазген Арутюнян - avatar
0
Seb TheS thanx, it makes it a lot easier when there are many elements in the statement
26th Jan 2020, 10:31 PM
Goran