1

Example 1 - This works:

def thisorthat():
    var = 2

    if (var == 3 or var == 2):
        print "i see the second value"
    elif (var == 2 or var == 15):
        print "I don't see the second value"

thisorthat()

Example 2 - This does NOT work:

def thisorthat():
    var = 2

    if var == (3 or 2):
        print "i see the second value"
    elif var == (2 or 15):
        print "I don't see the second value"

thisorthat() # "I don't see the second value"

Is there a way to compare a variable to an "OR" operator without repeating the variable twice in each line?

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
dzny
  • 364
  • 1
  • 7

2 Answers2

6

Here is an equivalent way:

if var in [2, 3]:
    ...
elif var in [2, 15]:
    ...

and you are using var only once per condition.

Notes:

  • This is not using OR directly.
  • The 2 in the second condition doesn't really make sense.
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

Explanation of what you are doing wrong:

In Python, or doesn't always work like in English. It takes two arguments and sees if either of them has the boolean value True (returning the first one that does). All non-zero numbers have the boolean value True, so var == (3 or 2) is evaluated to var == 3, which as var is 2, evaluates to False. When you do var == (2 or 15), you get var == 2, which is true, so the code below that elif statement is executed.

Like has been suggested, you should do var in (3, 2) instead.

rlms
  • 10,650
  • 8
  • 44
  • 61