3

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?

cs95
  • 379,657
  • 97
  • 704
  • 746
tomordonez
  • 341
  • 2
  • 15
  • 2
    Possible duplicate of [Does Python support short-circuiting?](https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting) – OneCricketeer Aug 31 '17 at 05:14
  • Your script isn't the same logic. That's why you have no errors. By the way `max([5, 20, 11])` works fine – OneCricketeer Aug 31 '17 at 05:15

2 Answers2

6

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!
cs95
  • 379,657
  • 97
  • 704
  • 746
0

If you examine your code carefully, you'll notice that you initialize largest to None, then conditionally ask if it is None, thus the if statement evaluates as True.

anon01
  • 10,618
  • 8
  • 35
  • 58