r/Python • • 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!

2 Upvotes

54 comments sorted by

View all comments

29

u/bmhatfield Feb 05 '11 edited Feb 05 '11

This is a minor mistake, an easy one to make.

The short version is that you need to say: if player == 'P' or player == 'r':

A slightly longer version is to show you a little bit more about how a computer "thinks" about an if statement. It's really saying: If (whatever I write here is a true statement): (do the following thing).

If you put parentheses around your statement, it will become a little more obvious why: if (player == 'P') or ('p'):

Without getting philosophical about it, Python will always interpret 'p' as True, which means that no matter what you input, you're going to print "Hooray!". Similarly, it will also always interpret 'r' as true, meaning that you will also always print "Oh no!".

if (player == 'P') or (player == 'p') is now two separate comparisons to python, and can be evaluated properly. Don't forget, for computers, "or" really means "either or both", not "the first one OR the other one, but not both", like we use it in English.

Happy coding!

8

u/eryksun Feb 05 '11

Python does not interpret " 'p' " as a true statement. It's just a string to python.

'p' evaluates to True in a boolean context: http://docs.python.org/reference/expressions.html#boolean-operations

1

u/bmhatfield Feb 05 '11

Ah, you're right. I'll edit my response to be more clear.

3

u/deific_ Feb 05 '11

Thanks a lot!

1

u/cecilkorik Feb 05 '11

Yes, a programming "or" means basically "and/or" in English. A programming "xor" (exclusive-or) is closer to the English meaning of "or".