Why can I pass "if largest is None or largest < num:" but not "if largest < num:"

Question:

When I try to pass " but not "if largest < num:" I get "TypeError: ‘<‘ not supported between instances of ‘NoneType’ and ‘int’". Which means I can’t compare NoneType and integers. But wouldn’t that still be the case for "if largest is None or largest < num:"?

largest = None
smallest = None
while True:
        num = input("Enter a number: ")
        if num == "done":
            break
        try:
            num = int(num)  
            if largest is None or largest < num:
                largest = num
            if smallest is None or smallest > num:
                smallest = num 
        except:
            print("Invalid input")
            continue
print("Maximum is", largest)
print("Minimum is", smallest)
Asked By: Mohammed Abdullah

||

Answers:

To explain, here’s an example:

if True or (1 < None):
    print('yep')

if 1 < None:
    print('this does not print, because the above throws an exception')

Prints yep but then TypeError: '<' not supported between instances of 'int' and 'NoneType'.

The reason this happens is, as @shadowranger indicated in comments, that logical operators like or and and short-circuit.

For or, that means that when evaluating P or Q, if P evaluates to True, there’s no need to evaluate Q, since the expression will be True regardless – so Python doesn’t.

Similarly, for and, it means than when evaluating P and Q, if P evaluates to False, there’s no need to evaluate Q, since the expression will be False regardless – so Python doesn’t.

So, you can see why this won’t throw an exception, since the offending code never gets executed:

if True or (1 < None):
    print('yep')
Answered By: Grismar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.