This question already has an answer here:
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"
The above expression tests whether or not
"Jesse"
evaluates toTrue
. If it does, then the expression will return it; otherwise, it will return"jesse"
. The expression is equivalent to writing:Because
"Jesse"
is a non-empty string though, it will always evaluate toTrue
and thus be returned:This means that the expression:
is basically equivalent to writing this:
In order to fix your problem, you can use the
in
operator:Or, you can lowercase the value of
name
withstr.lower
and then compare it to"jesse"
directly:The
or
operator returns the first operand if it is true, otherwise the second operand. So in your case your test is equivalent toif name == "Jesse"
.The correct application of
or
would be:would be the correct way to do it.
Although, if you want to use
or
, the statement would beevaluates to
'Jesse'
, so you're essentially not testing for'jesse'
when you doif name == ("Jesse" or "jesse")
, since it only tests for equality to'Jesse'
and does not test for'jesse'
, as you observed.If you want case-insensitive comparison, use
lower
orupper
: