Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Program for getting maximum and minimum value without using max and min function

Tags:

python-2.7

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
like image 631
Talha Javed Avatar asked Oct 20 '22 07:10

Talha Javed


1 Answers

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
like image 99
Quark Avatar answered Oct 22 '22 22:10

Quark