0

Does anyone know why this IF request in Python is returning true? Here is the code:

var1 = 1

if var1 == 100 or 50:
    print "yes"
else:
    print "no"

I can't work it out because var1 does not equal either 100 or 50.

jh314
  • 27,144
  • 16
  • 62
  • 82
user2804628
  • 133
  • 1
  • 13
  • 1
    If that's how your indentation looks it's not going to work. – kylieCatt Aug 07 '14 at 18:39
  • That's obviously not the problem or the user would have gotten a totally different error. It's clearly a new user that doesn't know how to format code here. – thumbtackthief Aug 07 '14 at 18:42
  • You might want to look at this: http://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html Operations closer to the top happen ahead of those lower on the list. Hence, var1 == 100 is evaluated first, that result is then or'd with 50 (which is always True). Short circuiting (another topic to look at) will skip the 'or' evaluation if the == result is True. – ScottO Aug 07 '14 at 20:17

3 Answers3

3

For the if statement, it reads if (var1 == 50) or 50

50 is True, so "yes" is printed out.

If you want to see if var1 is 100 or 50, you can do this:

var1 = 1

if var1 == 100 or var1 == 50:
    print "yes"
else:
    print "no
jh314
  • 27,144
  • 16
  • 62
  • 82
2

This if var1 == 100 or 50: is not working the way you think it is.

Using parenthesis it actually looks like this if(var1 == 100) or 50.

50 is not zero (zero is inherently False, integers that are not zero, positive or negative, are inherently True) so it will always evaluate True

Use this instead:

if var1 in (100,50):

kylieCatt
  • 10,672
  • 5
  • 43
  • 51
0

I think your semantics is incorrect:

if var1 == 100 or var1 == 50:

Seems more likely.

heinst
  • 8,520
  • 7
  • 41
  • 77
durbnpoisn
  • 4,666
  • 2
  • 16
  • 30