0

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)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • 4
    `or` short-circuits; if the left side is true the whole expression is definitionally true already (by boolean logic rules), so the right side isn't even evaluated. – ShadowRanger Jul 27 '22 at 01:05
  • Your code works fine on my computer. Please check your environment again. Do you save your code already. – ramwin Jul 27 '22 at 01:11
  • @ramwin the question is about why it works. OP expects it not to. – Karl Knechtel Jul 27 '22 at 01:17

1 Answers1

1

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')
Grismar
  • 27,561
  • 4
  • 31
  • 54