Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading