Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "No" as raw_input in the following python code returning TRUE?

Tags:

python

boolean

I cannot for the life of me understand why I can't get to the "else" statement no matter what I type. Any insight would be much appreciated. Am I not allowed to use more than one "or"?

print "Do you want to go down the tunnel? "

tunnel = raw_input ("> ")

if tunnel == "Y" or "Yes" or "Yea" or "Si" or "go" or "Aye" or "Sure":
    print "You found the gold."
else:
    print "Wrong answer, you should have gone down the tunnel. There was gold down there."
like image 274
onemicah Avatar asked Nov 30 '22 03:11

onemicah


1 Answers

Because in python

if tunnel == "Y" or "Yes" or "Yea" or "Si" or "go" or "Aye" or "Sure":

is equivalent to

if (tunnel == "Y") or ("Yes") or ("Yea") or ("Si") or ("go") or ("Aye") or ("Sure"):

and a nonempty string is true.

You should change your code to

if tunnel in ("Y", "Yes", "Yea", "Si", "go", "Aye", "Sure"):

or, to accept variations in capitalization:

if tunnel.lower() in ("y", "yes", "yea", "si", "go", "aye", "sure"):

or maybe even use a regex.

In Python 2.7 and more, you can even use sets, which are fasters than tuples when using in.

if tunnel.lower() in {"y", "yes", "yea", "si", "go", "aye", "sure"}:

But you really will get the perf boost from python 3.2 and above, since before the implementation of sets litterals is not as optimised as tuples ones.

like image 93
sverre Avatar answered Dec 04 '22 02:12

sverre