'Different Results With Parentheses and Variable Placement in Python 'or' Conditional? [duplicate]
When I run this program like this:
jonathan = 15
anthony = 25
if (jonathan or anthony) >= 21:
print("They can enter the building together.")
else:
print("They are not allowed to enter the building together.")
It outputs: They are not allowed to enter the building together.
However, when I run the program like this:
jonathan = 15
anthony = 25
if (anthony or jonathan) >= 21:
print("They can enter the building together.")
else:
print("They are not allowed to enter the building together.")
It outputs: They can enter the building together.
I was under the impression that the placement of the variable in this conditional if statement didn't matter if I was using the or keyword, since a conditional test with the or keyword passes if either one of the variables pass the test.
I do notice however that when I run the program like this, where jonathan is first again, and everything is included in the parentheses:
jonathan = 15
anthony = 25
if (jonathan or anthony >=21):
print("They can enter the building together.")
else:
print("They are not allowed to enter the building together.")
It outputs: They can enter the building together.
It would be greatly appreciated if one or more of you could explain to me the reasoning behind why the positioning of the variable & parentheses matters here in this condition with or.
I'm by no means an expert but from my point of view, it would probably be safest to use the last method where everything is in parentheses, including the >=21.
Thank you.
Solution 1:[1]
Python evaluates boolean conditions lazily meaning python only evaluates what is necessary to determine the boolean value of the statement
For example
True or 0/0
>>> True
since True or ... evaluates to True, Python stops evaluating the statement after it sees the first True
Similarly
False and 0/0
>>> False
since False and ... evaluates to False, Python stops evaluating the statement after it sees the first False
Using this to describe the behavior in your example
(jonathan or anthony) >= 21
(15 or 25) >= 21
15 >= 21
False
and
(anthony or jonathan) >= 21
(25 or 15) >= 21
25 >= 21
True
Since positive integers evaluate to True, the or statements return the first value and compare it 21.
In the last example
(jonathan or anthony >= 21)
(15 or 25 >= 21)
15
True
you just get the value of jonathan, a positive integer, so the statement evaluates to True
That being said, I assume this is not the behavior you want. I assume you want to compare the values of both anthony and jonathan to 21, and the syntax for that is:
anthony >= 21 or jonathan >= 21
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
