When writing code, it's crucial to understand how operations involving multiple values are interpreted. In Python, certain logical operators behave differently than their apparent English counterparts. Consider the following code:
name = input("Hello. Please enter your name: ") if name == "Kevin" or "Jon" or "Inbar": print("Access granted.") else: print("Access denied.")
This code attempts to grant access to users named "Kevin", "Jon", or "Inbar". Surprisingly, it grants access even to unauthorized users like "Bob". Why does this happen?
The or operator in Python doesn't follow the conventional English meaning strictly. When applied to multiple expressions, it chooses the first expression that evaluates to True. In the given code:
if name == "Kevin" or "Jon" or "Inbar":
is logically equivalent to:
if (name == "Kevin") or ("Jon") or ("Inbar"):
Since "Kevin" is True, the if block executes regardless of the value of name. This means that every user, including unauthorized ones, gains access.
To properly compare a value to multiple others, there are several recommended methods:
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"]):
To illustrate how Python parses logical expressions with multiple values, here's an example using the ast module:
import ast expr = ast.parse("a == b or c or d or e", "<string>", "eval") print(ast.dump(expr, indent=4))
This code reveals that the expression is parsed as follows:
Expression( body=BoolOp( op=Or(), values=[ Compare( left=Name(id='a', ctx=Load()), ops=[ Eq()], comparators=[ Name(id='b', ctx=Load())]), Name(id='c', ctx=Load()), Name(id='d', ctx=Load()), Name(id='e', ctx=Load())]))
As you can see, the or operator is applied to four sub-expressions: the comparison a == b and the simple expressions c, d, and e. This clarifies why the parsing behaves as it does.
The above is the detailed content of Why Does Python's `or` Operator Behave Unexpectedly with Multiple Values?. For more information, please follow other related articles on the PHP Chinese website!