Tuesday, September 24, 2019

python - Why does checking a variable against multiple values with `OR` only check the first value?




I want to check if a variable has one of multiple values. I'm confused about why or doesn't work in this situation. I was following a tutorial that gave the example if (a or b):, but when I try to do this it only checks the variable against the first value. What is wrong with my check?



name = raw_input('Please type in your name:')

if len(name) < 5:
print "Your name has fewer than 5 characters"
elif len(name) == 5:
print "Your name has exactly 5 characters"

if name == ("Jesse" or "jesse"):
print "Hey Jesse!"
else:
print "Your name has greater than 5 characters"

Answer



("Jesse" or "jesse")


The above expression tests whether or not "Jesse" evaluates to True. If it does, then the expression will return it; otherwise, it will return "jesse". The expression is equivalent to writing:




"Jesse" if "Jesse" else "jesse"


Because "Jesse" is a non-empty string though, it will always evaluate to True and thus be returned:



>>> bool("Jesse")  # Non-empty strings evaluate to True in Python
True
>>> bool("") # Empty strings evaluate to False
False

>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>


This means that the expression:




name == ("Jesse" or "jesse")


is basically equivalent to writing this:



name == "Jesse"






In order to fix your problem, you can use the in operator:



# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):


Or, you can lowercase the value of name with str.lower and then compare it to "jesse" directly:



# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...