5

I wrote the code below for getting max and min values as part of my MOOC assignment. This program continuously takes input from the user until the user types 'done'.

Once 'done' is typed, the program gives the results for max and min values. The problem is that the result for max value is always correct, but the result for min value is always "None".

largest = None
smallest = None
while ( True ) :
    inp = raw_input('Enter a number: ')
    if inp == 'done' :
        break
    try:
        inp = float(inp)
    except:
        print 'Invalid input'
    continue
    if inp is None or inp > largest:
        largest = inp
    if inp is None or inp < smallest:
        smallest = inp
print largest, smallest

1 Answer 1

3

The code you posted gives None for both largest and smallest. There is a continue statement after you try catch, so obviously it just keeps taking input and never terminates. continue will tell the loop to skip to the next iteration. So the continue has to come in the except block (this is probably an indentation mistake). Secondly, you are comparing input with None. I guess that was a typo in you if condition (it should be 'if largest is None' not 'if inp is None')

Modified code: (check last 2 if conditions):

largest = None
smallest = None
while ( True ) :
    inp = raw_input('Enter a number: ')
    if inp == 'done' :
        break
    try:
        inp = float(inp)
    except:
        print 'Invalid input'
        continue
    if largest is None or inp > largest:
        largest = inp
    if smallest is None or inp < smallest:
        smallest = inp
print largest, smallest
Sign up to request clarification or add additional context in comments.

2 Comments

You want the continue statement inside the except block otherwise who knows what inp is (like a string!)
The intention of except block is that if user input something other than numeric value like strings or some other data type it just print Invalid Input and go back to beginning because we don't need any other data type. And I've done this assignment. Well thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.