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
Release: 2024-12-21 04:16:14
Original
533 people have browsed it

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.")
Copy after login

Access is granted even to unauthorized users because Python evaluates this expression as:

if (name == "Kevin") or ("Jon") or ("Inbar"):
Copy after login

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":
Copy after login
  • Employ a collection:
if name in {"Kevin", "Jon", "Inbar"}:
Copy after login
  • Utilize any() and a generator expression:
if any(name == auth for auth in ["Kevin", "Jon", "Inbar"]):
Copy after login

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
Copy after login

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(...)])
Copy after login

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 of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template