The order of operations in Python

Viewed 49

I'm trying to understand the order of operators in Python. I tried the following:

var1 = None
var2 = 0
print( (var1 is None) != var2 )
print( (var1 is None) != var2 is True )     ###
print( ((var1 is None) != var2) is True )
print( (var1 is None) != (var2 is True) )
print( True is True )

I expected all to be True. However the result is:

True
False
True
True
True

How could the second print() gives me a False result?

1 Answers

This is due to comparison chaining, so this (perhaps surprisingly) simplifies to

>>> None == 0 is True
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False
>>> None == 0 and 0 is True
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
False

Some other examples

>>> 1 is 1 is 1
<stdin>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
True
>>> 1 < 2 < 3 < 4 < 5
True
>>> 4 < 2 < 3
False
>>> multiplayer_sandwich_order = "€35"
>>> 10 < int(multiplayer_sandwich_order[1:]) < 40
True
>>> 10 < int(multiplayer_sandwich_order[1:]) < 30
False
Related