Home >Backend Development >Python Tutorial >Why Does `name == 'Kevin' or 'Jon' or 'Inbar'` Always Evaluate to True in Python?
Why Does Assignment Using Or Always Evaluate to True?
When comparing multiple values using logical operators, Python's behavior may diverge from our intuitive understanding. For instance, in the code:
name = input("Hello. Please enter your name: ") if name == "Kevin" or "Jon" or "Inbar": print("Access granted.") else: print("Access denied.")
Access is granted even to unauthorized users because Python evaluates this expression as:
if (name == "Kevin") or ("Jon") or ("Inbar"):
In this case, the result is True for any name since "Jon" and "Inbar" are treated as independent logical operands.
How to Compare a Value to Multiple Others
To correctly compare against multiple values:
if name == "Kevin" or name == "Jon" or name == "Inbar":
if name in {"Kevin", "Jon", "Inbar"}:
if any(name == auth for auth in ["Kevin", "Jon", "Inbar"]):
Performance Comparison
For readability and efficiency, using a collection is generally preferred:
import timeit timeit.timeit('name in {"Kevin", "Jon", "Inbar"}', setup="name='Inbar'") # Faster timeit.timeit('any(name == auth for auth in ["Kevin", "Jon", "Inbar"])', setup="name='Inbar'") # Slower
Proof of Parsing Behavior
The built-in ast module confirms that expressions like a == b or c or d are parsed as:
BoolOp( op=Or(), values=[ Compare(left=Name(...), ops=[Eq()], comparators=[Name(...)]), Name(...), Name(...), Name(...)])
indicating that "or" is applied to individual comparisons and expressions.
The above is the detailed content of Why Does `name == 'Kevin' or 'Jon' or 'Inbar'` Always Evaluate to True in Python?. For more information, please follow other related articles on the PHP Chinese website!