I'm working on a security system that prevents access from unauthorized users.
import sys
print("Hello. Please enter your name:")
name = sys.stdin.readline().strip()
if name == "Kevin" or "Jon" or "Inbar":
print("Access granted.")
else:
print("Access denied.")
As expected, the above code allows access by authorized users, but also by unauthorized users.
Hello. Please enter your name:
Bob
Access granted.
Why is this happening? Obviously, I only allow access if name
is the same as Kevin, Jon, or Inbar. We tried to reverse the logic, such as if "Kevin" or "Jon" or "Inbar" == name
, but the results are still the same.
In many cases Python looks like a natural language and acts like it, but in this case it is one of the cases that it does not. One can contextually infer that "Jon" and "Inbar" are objects caught in the verb "same," but the Python interpreter accepts the original text as it is.
if name == "Kevin" or "Jon" or "Inbar":
is logically as follows:
if (name == "Kevin") or ("Jon") or ("Inbar"):
At this time, in the case of a user named Bob, it is replaced as follows:
if (False) or ("Jon") or ("Inbar"):
At this time, the or
operator selects the first factor with the true value
if ("Jon"):
Since "Jon" has a true value, the code block within the if
statement is executed. This allows access at all times regardless of the name value entered.
The if "Kevin" or "Jon" or "Inbar" == name
syntax is similarly true, so the code block within the if
statement is executed.
There are two common ways to create the conditional statement that you intend.
To use multiple ==
operators to compare each value:
if name == "Kevin" or name == "Jon" or name == "Inbar":
To use the in
operator by configuring the values to be compared as ordered pairs:
if name in ("Kevin", "Jon", "Inbar"):
© 2024 OneMinuteCode. All rights reserved.