Python Forum

Full Version: Python Assignment 5.2
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Anyone can assist me on what's my error since I can't figure out for hours...thanks so much!!!



Error:
ParseError: bad input on line 5
largest = None
smallest = None
while True:
    inp = raw_input('Enter a number: ')
        if inp == 'done': break
    try:
        num = int(inp)
        if largest is None or largest < num:
            largest = num
        elif smallest is None or smallest > num:
            smallest = num
    except:
        print('Invalid input')
        continue
print("Maximum is", largest)
print("Minimum is", smallest)
First observation is that if statement should not be intended. It should be on same level as inp.

inp = raw_input('Enter a number: ')
        if inp == 'done': break
it works after I change to below. Thanks for your feedback!

largest = None
smallest = None
while True:
    inp = raw_input('Enter a number: ')

    if inp == 'done':
        break

    try:
        num = int(inp)
        if largest is None or largest < num:
            largest = num
        elif smallest is None or smallest > num:
            smallest = num
    except:
        print('Invalid input')
        continue
print("Maximum is", largest)
print("Minimum is", smallest)
I advise to be specific about errors. You don't want silence all errors in your code. You want to handle only errors arising from user input which can't be converted to int. So my suggestion to change row 15 to this:

except ValueError:
From The Zen of Python:

Quote:Errors should never pass silently.
Unless explicitly silenced.

You should explicitly silence one error, not all errors.

Out of curiosity - what is wording of assignment 5.2?