r/learnpython • u/[deleted] • Apr 19 '14
'or' in 'if' commands
Quick question: I want either 'yes' or 'y' to be acceptable as an input. But the below code doesn't work - any idea why? (the indentations haven't come out right, but they're correct in the file)
if another.upper() == ('Y' or 'YES'):
print 'It worked'
The above will print 'it worked' if another.upper == 'Y', but not if it equals 'YES'.
Of course, I could use the following, but the previous is surely smarter!
if another.upper() == 'Y' or another.upper() == 'YES':
print 'It worked'
5
u/amertune Apr 19 '14
The answers that use in ('Y', 'YES') are correct, as are the explanations for why what you're doing isn't what you intended.
If you wanted to do the same thing with an or, you'd have to do it like this:
if another.upper() == 'Y' or another.upper() == 'YES':
print 'It worked'5
Apr 19 '14 edited Apr 20 '14
People have answered your question to get it working, but not really why. Parenthesis (these brackets) are used for a number of purposes in python.
The first is to create tuples (edit: see blahdom's reply) or generators. This happens when there is a list in the middle, either separated by commas, or a list comprehension:
my_tuple = (1, 2, 3, 4)
my_generator = (a for a in range(10))The second is for function definitions:
def my_function(my_argument):
passThe third use of parentheses is for logic order of operations. This is what happened in your first case. Let's look at the argument without them first:
if another.upper() == "Y" or "YES":In this, the == has a higher "precendence" than the "or" operator. So we first check whether another.upper() is equal to "Y". We would then check if "YES" is "truthy", i.e. does it equate to True. In this case it does (for strings: any non-empy string is True, any empty string is False).
Now, parentheses are used to change the order of operations, because anything in them is executed first.
if another.upper() == ("Y" or "YES"):In this example, we start by looking at the ("Y" or "YES") bit. Using or here will return the first "truthy" string, in this case "Y". This isn't really common usage, and you should probably stay away from this behaviour while you are learning. After we return "Y", we then check the == to see if another.upper() is equal to it. This is why your code was working with "Y" and not "YES".
A list of the order of operations is here if you want to learn more. This sort of thing is useful, but it is almost safer to use either simple comparisons, or to put brackets around things you want evaluated first.
4
u/blahdom Apr 20 '14
Just to correct one slight thing, parens don't make tuples, the comma makes the tuple. This is only really an important distinction when making a single element tuple
a = 1, # single element tuple b= (1) # b just is equal to the number one c = 1,2,3,4 # c is a tuple with elements 1 2 3 and 42
3
u/Swedophone Apr 19 '14
('Y' or 'YES')
This expression always evaluates to 'Y'!
Try the following instead:
if another.upper() in ('Y', 'YES'):1
u/zahlman zahlman Apr 20 '14
Sorry for boring you with a very long response, but this is the single most common beginner mistake by a huge margin, and you absolutely must understand it in great detail to advance as a programmer, or you will only continue to make related mistakes resulting from fuzzy thinking. I'm going to try to cover everything from the good existing replies, and just a little bit more.
Stop thinking "commands". We have statements, and expressions.
An expression is the same kind of thing as in mathematics: a tree of operands (values, or names of things) and operators (function calls, mathematical operators, comparisons etc.).
or is one example of an operator. It works like this:
Figure out the value of the sub-expression on the left-hand side of
or.Is it 'true'? If it is, then the whole thing evaluates to this value.
Otherwise, figure out the value of the sub-expression on the right-hand side, and use that instead.
In English, when you say "if this thing is 'Y' or 'YES'...", what you really mean is "Here is a set of things: {'Y', 'YES'}. If this thing is in the set...". You're giving all the options for what the thing might be equal to in order to satisfy your condition. However, this relies on a very imprecise, natural-language meaning of "or" that is not available in Python (or any other programming language I have heard of). In fact, it also relies on a very imprecise, natural-language meaning of "is".
So when you try to "translate" that directly to Python, what you get is the strict, not-natural-language interpretation: "Here are two possibliities: (a) this thing is equal in value to 'Y'; (b) 'YES' (i.e.: the string 'YES' is non-empty). If either of those is the case..." You cannot fix this with parentheses, because you're still stuck with the non-English or looking at 'Y' and 'YES' and evaluating it to 'Y'. Even if that worked, and gave you the set of possibilities somehow, you'd still be stuck with == being a comparison for equality. (In fact, the English "is" would no longer even do what you want.)
As it happens, though, Python does have a direct translation for the "here is a set of things" concept: the set type. Better yet, you can construct one directly, rather like you can with a list - the only difference is you use {} instead of []. (And in fact, we could use a list for what we're about to do; but the set is a better match for what we actually mean.)
And as it also happens, Python does have a direct translation for the "is this thing in the set" concept: the in keyword. This lets you write code that means exactly what you want and still reads like English:
if another.upper in {'Y', 'YES'}:(And as it happens, Python also has an is keyword, but it doesn't help us here - it's actually more strict than ==, because it basically checks whether the two sides evaluate to the same specific object, instead of just comparing whether those objects are equal to each other.)
0
Apr 19 '14
Thanks for all the great answers here! It's rather odd that my version doesn't work, but I like your versions better!
16
u/ruicoder Apr 19 '14
It's not odd. ('Y' or 'Yes') is a boolean expression, not a list of values. Try it in your interpreter:
>>> ('Y' or 'Yes') 'Y''Y' evaluates to True so python returns 'Y'.
8
u/fruitcakefriday Apr 19 '14 edited Apr 20 '14
When you use the 'or' operator in that first context, Python returns either:
The first value that is
Truein the statement.The last value, if both values are
False.Example:
>>> print ('something' or 'something_else') something >>> print ('' or 'something_else') something_else >>> print ('' or 0) 0 >>> print (0 or '') # an empty stringAlso, using 'and' in the same context will return either
The first value that is
Falsein the statement.The last value, if both values are
True.Example:
>>> print (0 and '') 0 >>> print ('' and 0) # an empty string >>> print ('one' and 'two') twoThis is quite useful, for example if you want the value from a function, but if the function returns nothing, then something else. Say you have a function,
getDeliciousFood(), that returns a random delicious food type, but can also return nothing. You may want to substitute that nothing with something else, like bread:my_dinner = getDeliciousFood() or 'bread'4 executions of that same statement might result in, 'lobster', 'pizza', 'curry', and then 'bread', or those in any other order, or 4 breads, or none, or whatever.
6
0
u/Miggol Apr 19 '14
I don't know why your version doesn't work, but the way I'd go about it is
if another.upper() in ['Y', 'YES']:
print 'It worked'It's cleaner and allows many more acceptable answers.
20
u/DMzda Apr 19 '14
The statement
("Y" or "YES")will return the firstTrueitem, which is"Y". This means that your first statement becomes:What you should use is the
inoperator with a list: