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

I can’t understand why I don’t understand why I can’t go to "else" no matter what I type. Any insight would be greatly appreciated. Am I not allowed to use multiple "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." 
+4
source share
2 answers

Because in python

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

equivalently

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

and a nonempty string is true.

You must change your code to

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

or, to accept changes in capitalization:

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

or even use regex.

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

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

But you really will get a level upgrade from python 3.2 and higher, since before implementation of the litterals sets it is not as optimized as tuples.

+23
source

As in the answer above, when using the str type for bool only an empty string returns false:

 >>> bool("") False >>> bool("No") True >>> 

So when you say:

 if (tunnel == 'y') or 'foobar': print('woo') 

this operator will be calculated as follows:

 if (tunnel == 'y') or True: print('woo') 

The moral of this story is that it’s a good idea to have a translator working while editing the code, then you can try out small pieces of complex expressions before you assemble them :)

-1
source

Source: https://habr.com/ru/post/1390271/


All Articles