0
x = 5
if x == 2 or 4 or 6:
    print("Even")
elif x == 3 or x == 5 or x == 7:

    print("Odd")

I know the or statements should be like the bottom line but I am curious to why when run the output is always even, despite it not being in the if line. When run with the top line like the bottom it works however it treats the bottom as an else so if x was 30 it would still fall into 'odd'. Any explanation to why this is would be greatly appreciated.

1 Answers1

0

In boolean contexts python implicitly calls bool buitlin on the operands if they're not boolean already to evaluate their truth value but does not constitute them with a boolean, and note that python logical and and or are short-circuit so python starts with x == 2 which is False so it continues and sees number 4 and calls bool(4) which evaluates to True so the whole line returns 4: if 4: and because integers have a boolean value of True you whole condition evaluates to True.

Masked Man
  • 2,176
  • 2
  • 22
  • 41
  • This is not entirely correct. ``bool`` is called on the entire expression, not on its constituents. The boolean value of ``4`` and ``6`` is momentarily computed, but not propagated. The expression ``x == 2 or 4 or 6`` evaluates to ``6``, not ``True``. – MisterMiyagi Apr 21 '20 at 12:35
  • I disagree with you, you can define a custom class and override it's `__bool__` method to see when it is called, the logical operators are short-circuit in python. – Masked Man Apr 22 '20 at 11:12
  • bool is called on the number to decide which branch to take. This is different from using the result of bool instead of the original branch, as the answer initially implied. – MisterMiyagi Apr 22 '20 at 11:29
  • I updated the answer to be more precise and correct now, and the branch will not go as far to reach the number **6**. – Masked Man Apr 22 '20 at 11:41