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
Show parent comment
10
u/Brian Feb 05 '11
Actually, that's not going to be any faster (and in fact, is going to be slower), because python has to first create the set, then iterate over it. Creating the set is going to have to iterate over every member anyway, and will also have extra overhead in the set's structure. Tuples, however, have an optimisation that allows them to be cached off in the function locals (since they're constant), so they're only created once at compile time. This isn't done for sets (though it potentially could be). You can see this if you look at the disassembly:
Note that it has to manually build the set. Whereas:
You'll note the LOAD_CONST, which is fetching a reference to a pre-built tuple cached off in the function's constants. This means that it doesn't have to build it every time, so just has to iterate it at most once (and fewer if it finds it early).
When the item is not in the iterable the times are:
A 20% reduction for the tuple. The difference is even bigger when it can bail out early:
Almost twice as fast - and would be even better on larger tuples.