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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With