TAGS :Viewed: 14 - Published at: a few seconds ago

[ get numbers from user & print maximum and minimum (w/o using built-in function) ]

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!

Answer 1


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

Answer 2


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))

Answer 3


input_set = []
input_num = 0

while (input_num >= 0):

    input_num = int(input("Please enter a number or -1 to finish"))
    if (input_num < 0):
        break
    input_set.append(input_num)

print(input_set)

largest = input_set[0]
for i in range(len(input_set)):

    if input_set[i] > largest:
        greatest = input_set[i]

print("Largest number is", greatest)



smallest = input_set[0]
for i in range(len(input_set)):

    if input_set[i] < largest:
        smallest = input_set[i]

print("Smallest number is", smallest)