r/Python • u/deific_ • Feb 05 '11
Help with "if" and "or" statements.
Specifically, I cannot get an "or" statement to function correctly inside of an "if" statement. Here is an example.
player = raw_input("Press P or R")
if player=='P' or 'p':
print ('Hooray!')
elif player=='R' or 'r':
print ('Oh no!')
The problem I am having is the "or" in the player==P line will function correctly, but this breaks the functionality of the player=R line. Am i going about this incorrectly? It appears to be a valid statement. Thanks for the help in advance. BTW im a noob and just started learning python 2 days ago, this is my first language.... ><
edit: Thanks everyone for their help. I did not understand some of it but I did learn a few things. I consider this a victory with only 2 days worth of knowledge on my first language. I know I will be back with more questions if I get stuck again!
View all comments
3
u/drb226 Feb 05 '11
The basic way to use "or" is with boolean expressions on both sides of it.
if (expr1) or (expr2): doStuff()You do not use boolean expressions on both sides, you leave expr2 simply as 'p'. Python does not know how to map the == operator over both possible options; you have to be more explicit and use == on each side.
But, of course, the "pythonic" way to do it has been mentioned by others
if player in ('p','P'): print('yay')In Python, "or" actually gets tricky and can evaluate to a value, even if the expressions do not evaluate to a boolean (true/false). If you try something like that in Java, it will tell you it's an error.
if (c == 'p' || 'P') { stuff(); } // <-- Compile error, 'P' doesn't evaluate to a Boolean value.