I am misunderstanding the OR operator

I entered the code below…

test = range(0,10)
for i in test:
    print(i)
    if i == 1 or 3 or 9:
        print(i)

What I expected to happen:
The output I expected was…
0
1
1
2
3
3
4
5
6
7
8
9
9

What actually happened:
0
0
1
1
2
2
3
3
4
4
etc.

Why is the conditional evaluating to true and printing out every number twice?

1 Like

Right way is to do

if i == 1 or i == 3 or i == 9:

In this case if i == 1 or 3 or 9 It would return 3 each time when i == 1 is false. So it will be always true. See here about or operator behavior

>>> i = 1
>>> i == 1 or 3 or 9
True
>>> i = 2
>>> i == 1 or 3 or 9
3
>>> i = 3
>>> i == 1 or 3 or 9
>>> 3

This Return 3 if first condition is false So in if condition it will passed always; as any digit consider True except 0 ; (0 is equivalent False) hence

>>> if 3:
...   print("Condition is True")
...
Condition is True
2 Likes