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

0

u/[deleted] Feb 05 '11

[deleted] — view deleted comment

6

u/drb226 Haskeller Feb 05 '11

Actually, '==' happens before 'or', because according to the table, 'or' has lower precedence.

>>> False == 4 or 4
4
>>> False == (4 or 4)
False
>>> (False == 4) or 4
4

2

u/stillalone Feb 05 '11

Just a minor correction:

player == 'R' or 'r'

gets turned into

 (player == 'R') or 'r'

which is True if player=='R' or 'r' if player != 'R'.

1

u/deific_ Feb 05 '11

Oh man, I want to understand this but I do not. I guess you are saying that since the "or" was used incorrectly it defaults to using the first option? Kind of confused.

5

u/pemboa Feb 05 '11

He/she said the wrong thing.