Why do I get a TypeError?

Question:

Im stuck with this problem I get a TypeError when trying to compare a None Value.

TypeError: ‘>’ not supported between instances of ‘int’ and ‘NoneType’

max_val = None
min_val = None
num = 0

while True:
    num = input("enter a number: ")
    if num == 'done':
        break
    try:
        inum = int(num)
    except:
        print('Invalid input')
        continue

    if min_val is None:
        min_val = inum

    if inum > max_val:
        max_val = inum

    elif inum < min_val:
        min_val = inum

print('Maximum is ', max_val)
print('Minimum is ', min_val)
Asked By: ivanoyca

||

Answers:

The first time through, both min_val and max_val are None, so that case needs to be handled. You can also skip the comparisons that follow the first time through:

    if min_val is None:
        min_val = inum
        max_val = inum

    elif inum > max_val:
        max_val = inum

    elif inum < min_val:
        min_val = inum
Answered By: Tom Karzes

You can use infinity and negative infinity as type-compatible alternatives to None.

max_val = -float('inf')  # x > -float('inf') for any int x
min_val = float('inf')  # x < float('inf') for any int x

while True:
    num = input("enter a number: ")
    if num == 'done':
        break

    try:
        inum = int(num)
    except:
        print('Invalid input')
        continue

    if inum > max_val:
        max_val = inum

    if inum < min_val:
        min_val = inum

print('Maximum is ', max_val)
print('Minimum is ', min_val)
Answered By: chepner
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.