0

Can anyone please help me understand why I am getting strange results to the following boolean expressions. All three of these code snippets should be "equivalent", but all produce different results. The results seem to contradict the python documentation surrounding operator precedence.

x = 1
y = 0
print(x > y)             #prints True
print(x > y == True)     #prints False  *?*
print(x > y == False)    #prints True   *?*
print( (x > y) == True)  #prints True
print( (x > y) == False) #prints False

Note how the 2nd & 3rd lines of output contradict the 4th and 5th.

And then in the following, the same 2 lines as above produce different results:

x = 2
y = 1
print(x > y)             #prints True
print(x > y == True)     #prints True  *?*
print(x > y == False)    #prints False  *?*
print( (x > y) == True)  #prints True
print( (x > y) == False) #prints False

And again below, again with even different results:

x = 8
y = 5
print(x > y)             #prints True
print(x > y == True)     #prints False  *?*
print(x > y == False)    #prints False  *?*
print( (x > y) == True)  #prints True
print( (x > y) == False) #prints False

This seems to also be related to the following apparent contradiction:

print(1 in [0, 1, 2, 3])           #prints True
print(1 in [0, 1, 2, 3] == True)   #prints False

I know the "== True" isn't needed, but its natural that a student first learning would use that expression as well.

Thanks!

0 Answers0