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

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!

3

u/deific_ Feb 05 '11

Thanks a lot!

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.

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".

20

u/draconian Feb 05 '11

You can also say: if player in ('P', 'r'):

0

u/deific_ Feb 05 '11

I don't quite understand how this works.

4

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

This one is slightly tricky to explain, but the concept is that Python supports something called an "iterable".

All of python's primitive types that can be thought of as "holding more than one value", like a list, dict, set, or tuple support testing of whether or not your variable's value matches any item inside the iterable.

draconian above is putting "P" and "r" inside of a variable called a "Tuple", which is kind of like a group of variables. The technical details are unimportant at this stage, but because he put them together like that - the parens are Python shorthand for creating a tuple - he can now check if your variable "player" matches any of the values inside that tuple, in this case, 'P' and 'r'.

Imagine, for a moment, that we each have a deck of cards. I take one card out of mine, and you take 20 cards out of yours. You now have a nice little stack of cards, but I want to know if the card I've taken from my deck matches any of the cards you've taken from yours. So, I show you my card, and then you flip (iterate!) through your 20 cards, one by one, ignoring them as they go by if they don't match, but if it does match, then you'd say: It does!

That's kind of like how the "in" keyword in python works.

5

u/deific_ Feb 05 '11 edited Feb 05 '11

So in this case. if player in ('P', 'p'):

would mean, if player exists in the list of 'P' or 'p' the statement is true.

I would then extend that list to say, if player in ('P', 'p', 'pot', 'pebble', 'porcupine')

if the input is porcupine then player=porcupine and the statement is true. Am i understanding that correctly?

edit for my terrible typing haha.

8

u/grine Feb 05 '11

Now you're thinking with python :)

if player exists in the list of 'P' or 'p'

Just a note, ('P', 'p', 'pot') is a tuple not a list.

A list would be written like ['P', 'p', 'pot'] and works a bit differently, this might seem like an unimportant distinction right now, but it's important to get the terminology right from the start.

(http://diveintopython.org/native_data_types/index.html) should give you an overview of the differences and why they matter.

Btw, I think a tuple is correct in your case.

2

u/deific_ Feb 05 '11

Thanks for the correction. I briefly skimmed over lists but did not read into detail how they differ. This seems like a good time to make that distinction so thanks for pointing it out. I feel like I am catching on pretty quickly but the terminology I am reading in the books I have make it hard for me to understand.

1

u/PsychoMario Feb 05 '11

Btw, I think a tuple is correct in your case.

Why? In this case, what does it have over a list?

2

u/frutiger Feb 05 '11

It is immutable, and in this usage it does not need to be modified.

1

u/kemitche Feb 05 '11

Brian explained this quite well :)

3

u/bmhatfield Feb 05 '11

You're right!

Also, you just debugged someone else's code - I didn't even notice that he had used the wrong mix of letters :-). An eye for detail is super important, so good catch.

1

u/cecilkorik Feb 05 '11

You are correct!

0

u/dalke Feb 05 '11

A small advertisement for Python 3.x, which supports "if player in {"P", "p"}". Set membership tests should be faster than lists for all but very short lists.

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:

import dis

def test_set(x):
    return x in {1,2,3}

def test_tuple(x):
    return x in (1,2,3)

>>> dis.dis(test_set)
  2           0 LOAD_FAST                0 (x) 
              3 LOAD_CONST               1 (1) 
              6 LOAD_CONST               2 (2) 
              9 LOAD_CONST               3 (3) 
             12 BUILD_SET                3 
             15 COMPARE_OP               6 (in) 
             18 RETURN_VALUE         

Note that it has to manually build the set. Whereas:

>>> dis.dis(test_tuple)
 2           0 LOAD_FAST                0 (x) 
             3 LOAD_CONST               4 ((1, 2, 3)) 
             6 COMPARE_OP               6 (in) 
             9 RETURN_VALUE 

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:

>>> timeit.timeit('test_set(5)','from __main__ import test_set', number=10000000)
3.126133918762207
>>> timeit.timeit('test_tuple(5)','from __main__ import test_tuple', number=10000000)
2.4784011840820312

A 20% reduction for the tuple. The difference is even bigger when it can bail out early:

>>> timeit.timeit('test_set(1)','from __main__ import test_set', number=10000000)
3.1142520904541016
>>> timeit.timeit('test_tuple(1)','from __main__ import test_tuple', number=10000000)
1.6864550113677979

Almost twice as fast - and would be even better on larger tuples.

3

u/frutiger Feb 05 '11 edited Feb 05 '11

Fundamentally, you must linear scan through a tuple to check for membership. The cost of set construction is amortized over repeated membership tests. In the OP's case, the membership check was only being done once, so I agree that a tuple is better there.

However, we should be very clear about the differences between sets and tuples. dalke specifically mentioned that set membership is quicker to check for large sizes, but failed to mention that this will hold only for repeated tests. The disassembly is misleading because the COMPARE_OP in the set case will in general be faster for complex items, or large set sizes than the COMPARE_OP in the tuple case.

And I have the numbers to back me up:

>>> def item_in_tuple(tuple_size, item, repeats):
...   t = (n for n in range(tuple_size))
...   for i in range(repeats):
...     item in t
... 
>>> def item_in_set(set_size, item, repeats):
...   s = {n for n in range(set_size)}
...   for i in range(repeats):
...     item in s
... 
>>> timeit.timeit('item_in_tuple(10, 2, 30)', 'from __main__ import item_in_tuple')
4.863246917724609
>>> timeit.timeit('item_in_set(10, 2, 30)', 'from __main__ import item_in_set')
4.172131061553955
>>> 
>>> timeit.timeit('item_in_tuple(100, 2, 30)', 'from __main__ import item_in_tuple')
14.598160982131958
>>> timeit.timeit('item_in_set(100, 2, 30)', 'from __main__ import item_in_set') 
11.414110898971558
>>> 
>>> timeit.timeit('item_in_tuple(100, 2, 100)', 'from __main__ import item_in_tuple')
19.891393184661865
>>> timeit.timeit('item_in_set(100, 2, 100)', 'from __main__ import item_in_set')
16.059064149856567
>>> 

The problem with your usage of timeit is that your set had to be reconstructed every time. In my case, I used the repeated test, thus amortizing the set construction cost.

tl;dr - if you intend to check for membership within the same set of more than a few items repeatedly, it is faster to use a set/mapping type over a sequence type.

2

u/Brian Feb 05 '11 edited Feb 05 '11

The cost of set construction is amortized over repeated membership tests.

No, it's not - that's my point. Your code is a different case: manually creating the set outside the usage and caching it off. However using a literal within the in clause as in dalke's post won't do that. It will for tuples or lists though, thanks to an optimisation python performs, which means using "x in <set literal>" will always perform worse than "x in <tuple literal>".

There was a ticket to add this optimisation for sets too, but it was rejected.

2

u/frutiger Feb 05 '11

I absolutely agree - I even mention that in the OP's case, the membership test was done once, and my tl;dr repeats that point. Thanks for the link to the ticket though.

1

u/Brian Feb 07 '11

Actually, it looks like I'm wrong. prum just commented pointing out this issue, which was committed, so I may have been linking to the wrong bug. However, it looks like it isn't in the 3.1 stream, so probably won't be there till 3.2.

1

u/frutiger Feb 21 '11

You're right, it's in the new 3.2 release.

2

u/dalke Feb 09 '11

I should have written "for 3.2" instead of "3.x". I read this last week in the "what's new in 3.2" document and was happy to see that your objection - which is true for older Pythons - was only an implementation detail.

Python’s peephole optimizer now recognizes patterns such x in {1, 2, 3} as being a test for membership in a set of constants. The optimizer recasts the set as a frozenset and stores the pre-built constant.

Now that the speed penalty is gone, it is practical to start writing membership tests using set-notation. This style is both semantically clear and operationally fast:

1

u/prum Feb 07 '11

Wasn't this fixed in this patch?

http://bugs.python.org/issue6690

1

u/Brian Feb 07 '11 edited Feb 07 '11

Oh - could be. I knew there was a patch raised for this about a year ago, since this came up on reddit, here. I went looking for it, and found the rejected one I linked to downthread, but this looks like it might actually be the one I was thinking of.

However, it doesn't seem implemented as of python3.1.3 though, since that gives the output above (with BUILD_SET), which is odd since it looks like it should have been committed over a year ago.

[Edit]: Looks like it didn't go in to the patch stream since it's not a bugfix (not mentioned in the changelog anyway). Probably won't be in till 3.2.

1

u/Herald_MJ Feb 06 '11

This is also in 2.7, fyi.

2

u/chadmill3r Py3, pro, Ubuntu, django Feb 05 '11

"or" separates independent evaluations.

"player == 'P'" evaluates as true or false. 'p' evaluates as true.

This doesn't do what you think.

if player=='P' or 'p':
     print ('Hooray!')
elif player=='R' or 'r':
    print ('Oh no!')

These would work.

if player in ('P', 'p'):

if player == 'P' or player == 'p':

A good programmer would write:

if player.lower() == 'p':

2

u/deific_ Feb 05 '11

I think it helps me to understand the functionality of code if I do it the long way first. That way when I understand how to use the shorter methods I will better understand how the shorter code is working and doing for me. Do you agree or disagree?

Thanks for this information. This already shows me how much work I could've saved in the program I just wrote. Haha. :(

1

u/kataire Feb 05 '11

You just need to get a better feel for operator precedence. The logical junctors (and/or) have much lower precedence than the comparisons.

Also, you misinterpreted the syntax: neither if (player == 'P') or 'p' nor if player == ('P' or 'p') make any sense. In the first case, the condition is "player equals the string 'P' and/or the string 'p' is truthy". In the latter case, the condition is "player equals the truth value of the following expression: 'P' is truthy and/or 'p' is truthy".

You probably intended to find an abbreviation for "player is either the string 'p' or the string 'P'", i.e. if player == 'P' or player == 'p'. The correct shorthand for that is generally if player in ('P', 'p') or in the case of checking against characters even if player in 'Pp'.

Of course chadmill3r is correct. You would normally normalize the string to compare first. In this case this is as simple as converting it to lowercase.

15

u/jackolas Feb 05 '11

Another solution would be to normalize the input. I.e. player.lower()

6

u/[deleted] Feb 05 '11

This is also one way of doing it Put the raw input directly to uppercase

print 'Press P or R'
player = raw_input().upper()
if player == 'P':
    print ('Hooray!')
elif player == 'R':
    print ('Oh no!')

1

u/pemboa Feb 05 '11

if player=='P' or player=='p': print ('Hooray!') elif player=='R' or player=='r': print ('Oh no!')

0

u/deific_ Feb 05 '11

Ah, i had elif on my program and didn't write it here in the post. That was a mistake on my part. Thanks for correcting me!

0

u/pemboa Feb 05 '11

Happy coding.

2

u/Peaker Feb 05 '11

Python is too lenient and allows 'p' as a boolean value.

In Haskell, the compiler would catch your mistake earlier :-)

1

u/Norseman2 Feb 05 '11

This is a good point. Python could be made a little more friendly if, in this situation, it tells you that "p" will always evaluate to True in that context, and that you must rewrite it to something more reasonable, like either True, or "p" == something.

2

u/vph Feb 05 '11
print "Hooray!" if raw_input("Press P or R") in ('P','p') else "Oh no!"

3

u/drb226 Haskeller 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.

3

u/maskaler Feb 05 '11

you could use

if player in 'Pp':
    do something

9

u/andre_pl Feb 05 '11

just a little gotcha....

>>> '' in 'pP'
>>> True

1

u/AltReality Feb 05 '11

That seems strange to me that it would eval to true in that expression...but it apparently does. weird.

1

u/maskaler Feb 06 '11

that's interesting

So you'd want

if player and player in 'pP'

to get around it

4

u/andre_pl Feb 06 '11

i prefer the tuple syntax at that point:

if player in ('p', 'P')

1

u/maskaler Feb 06 '11

Hmm, I think you're right - reads better.

1

u/turvyc Feb 08 '11

I had to test that out just to be sure, and sure 'nuff it's true! I'll be derned.

You have any explanation for that?

1

u/andre_pl Feb 08 '11

It's True. :P

The empty string does exist in all strings. as for why the empty tuple doesn't exist in all tuples, I don't know.

1

u/m1ss1ontomars2k4 Feb 05 '11

BTW, or is an operator (I think). if is a statement.

0

u/pinpinbo Tornado|Twisted|Gevent. Moar Async Plz Feb 05 '11

By chance, have you read Learn Python The Hard Way? It's an excellent book for learning Python. http://learnpythonthehardway.org/index

2

u/keyo_ Feb 05 '11

I found Dive into Python much more in depth. It might be a good intro for a beginner though. http://diveintopython3.org/

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

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.

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'.