views:

81

answers:

2

I'm reviewing a python exercise which does the following :

  • reads list of numbers til "done" gets entered.

  • When "done" is inputted, print largest and smallest of the numbers.

  • And it should be without directly using the built-in functions, max() and min().

Here is my source. Traceback says, "'float' object is not iterable"

I think my errors are coming from not using the list properly to calculate smallest and largest. Any tips and help will be greatly appreciated!

while True:
    inp = raw_input('Enter a number: ')
    if inp == 'done' : 
        break

    try:
        num = float(inp)
    except:
        print 'Invalid input'
        continue                            

numbers = list(num)
minimum = None       
maximum = None

for num in numbers :                          
    if minimum == None or num < minimum :
        minimum = num

for num in numbers :        
    if maximum == None or maximum < num :
        maximum = num

print 'Maximum:', maximum
print 'Minimum:', minimum

Thank you!

+3  A: 

With num = float(inp) you only assign a single number and overwrite it each time a new one is assigned. You have to create the list first, then add numbers to it each time. Something like this:

nums = []
while True:
  ...
  nums.append(float(inp))
Frank
+3  A: 

You shouldn't need a list. You should only need to keep track of the current minimum and maximum as you go.

minimum = None
maximum = None

while True:
    inp = raw_input('Enter a number: ')
    if inp == 'done': 
        break

    try:
        num = float(inp)
    except:
        print 'Invalid input'
        continue                            

    if minimum is None or num < minimum:
        minimum = num

    if maximum is None or num > maximum:
        maximum = num

print 'Maximum:', maximum
print 'Minimum:', minimum
Mike DeSimone