Home >Backend Development >Python Tutorial >Why Does `name == 'Kevin' or 'Jon' or 'Inbar'` Always Evaluate to True in Python?

Why Does `name == 'Kevin' or 'Jon' or 'Inbar'` Always Evaluate to True in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-21 04:16:14462browse

Why Does `name ==

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:

  • Use multiple == operators:
if name == "Kevin" or name == "Jon" or name == "Inbar":
  • Employ a collection:
if name in {"Kevin", "Jon", "Inbar"}:
  • Utilize any() and a generator expression:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn