Zictrox
Zictrox

Reputation: 3

why does the code > if 3 == 1 or 2: print('A') else: print('B') < print A but not B

I recently started learning my first programming language and i couldn't understand why this code gave me A as the answer and not B

if 3 == 1 or 2:
    print('A')
else:
    print('B')

Upvotes: 0

Views: 774

Answers (3)

marco
marco

Reputation: 6655

You check for the two conditions 3==2 and 2. 2 evaluates to true, so you get A as output.

If you want to check 3 for beeing 1 or 2, you have to do it like this:

if 3 == 1 or 3 == 2: print('A') else: print('B')

See e.g. Do not understand why if condition evaluates to True when variable is integer for details why 2 is true, especially this answer.

Upvotes: 1

JohnLM
JohnLM

Reputation: 316

You have a wrong assumption that 3 == 1 or 2 means "is 3 equal to 1 or 2?", but in reality it's rather "is either 3 equal to 1, or does 2 evaluate to True" and since 2 is non-zero value it always evaluates to True.

More specifically, 3 == 1 or 2 expression evaluates to False or 2 then False or True and finally True.

If you want the expression that matches your original expectation, you should write 3 in [1, 2] which checks whether 3 is in one of the allowed values in the list.

Upvotes: 0

Dmitrii
Dmitrii

Reputation: 624

In python it could be read as if 3==1 or bool(2) == True where the first condition if False and the second is True because bool(2) is True

Upvotes: 0

Related Questions