Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No TypeError comparing int with None in Python3

I understand that comparing int and None types is not valid in Python3 (3.6.1) as I see here:

>>> largest = None
>>> number = 5
>>> number > largest
TypeError: '>' not supported between instances of int and NoneType

But inside this script it doesn't give a TypeError.

largest = None
for number in [5, 20, 11]:
    if largest is None or number > largest:
        largest = number

When I run this script with python3 it runs without a TypeError. Why?

like image 773
tomordonez Avatar asked Mar 21 '26 10:03

tomordonez


1 Answers

You're witnessing short circuiting.

if largest is None or number > largest:
        (1)        or      (2)

When condition (1) is evaluated to be true, condition (2) is not executed. In the first iteration, largest is None is True, so the whole expression is true.


As an illustrative example, consider this little snippet.

test = 1
if test or not print('Nope!'):
     pass

# Nothing printed 

Now, repeat with test=None:

test = None
if test or not print('Nope!'):
     pass

Nope!
like image 179
cs95 Avatar answered Mar 23 '26 00:03

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!