Unknown variable in interval comparison does not raises NameError

Viewed 34

I faced a very weird issue today with this simple code:

var1 = 1
var2 = 2

if var1 > var2 > var3:
    print('Does not run')

print('Did not crash')

Output:

Did not crash

Why isn't this code raising NameError with Python 3.7 ? Replacing the interval comparison with a simple comparison raises NameError as expected. Is this a python bug ?

1 Answers

var1 > var2 > var3 is equal to (var1 > var2) and (var2 > var3). First statement evaluates to False, so the second statement after the and is not evaluated at all because of Short-circuit evaluation.

Related