-2

Good morning,

My problem is the following:

if variable == 'string1':
  do_stuff
elif variable == 'string2' or 'string3':
  do_stuff2

It does not work as it should : do "stuff2" when variable equals "string2" or "string3".

To do that, I have to right the following code:

if variable == 'string1':
  do_stuff
elif variable == 'string2' or variable == 'string3':
  do_stuff2

This code works fine: when variable equals "string2" or "string3", the code excutes stuff2.

I do not understand what is the difference between : elif variable == 'string2' or variable == 'string3' and elif variable == 'string2' or 'string3'.

What does python understand in the second version ?

Thank you for your help,

Pado

Iron Fist
  • 10,739
  • 2
  • 18
  • 34
Pado
  • 21
  • 4
  • 1
    because that is the proper syntax for the boolean predicate you want to express – Pynchia Jan 08 '16 at 14:11
  • 1
    `variable == 'string2' or 'string3'` evaluates to `(variable == 'string2') or 'string3'`. – Nelewout Jan 08 '16 at 14:11
  • 1
    This is not a duplicate, it's a specific question about a problem Pado is having understanding the syntax. – Joe Jan 08 '16 at 14:16
  • Because `==` has a higher precedence than `or`. That means that in the second expression, `variable == 'string2'`is evaluated first. The python `or` operator will return the return value of the first operand if it is true, not just True or False. – Suzana Jan 08 '16 at 14:19
  • @Joe - It is a duplicate. The accepted answer says that the other expressions "are otherwise evaluated on their own (`False` if `0`, `True` otherwise)," which is the explanation for what happens with the `if variable == x or y or z` syntax. – TigerhawkT3 Jan 08 '16 at 14:21

2 Answers2

0

Does this help you to understand:

>>> x = 'Test'
>>> 
>>> x == 'Test1' or 'Test2'
'Test2' #Expression evaluated to value of 'Test2' as first was False
>>>
>>> x == 'Test1' or 'Test'
'Test' #Expression evaluated to value of 'Test' as first was False
>>>
>>> x == 'Test' or 'Test1'
True #Expression evaluated to True as x is truly 'Test'
>>>
>>> x == 'Test1' or x == 'Test'
True #Expression evaluated to True as second expression was True
Iron Fist
  • 10,739
  • 2
  • 18
  • 34
0

Try it in the REPL.

>>> "one" or "two"
'one'

This is the 'short circuiting or'. It returns the first non-False value.

The meaning of the 'or' operator is "is one or another value truthy?". The short-circuiting functionality, which returns the first truthy value is a bonus feature.

So your statement

elif variable == 'string2' or 'string3':

actually means

elif variable == 'string2':
Joe
  • 46,419
  • 33
  • 155
  • 245