1

I'm having trouble with a project for class and I was looking for some help. I need to make a code where it will ask for numbers repeatedly and then print out the min and max in the list. My teacher said we can do this anyway we wish.

   num_list = []
   while True:
   num = raw_input("Enter a number: ")
   if num == "done" : break
   if num >= 0:
   num_list.append(num)
   print min(num_list)
   print max(num_list) 

This is what I have so far, it asks for the number inputs and will break when I enter done, but it will only print out "Done" for the min and max in the list.

1 Answers1

1

you need to convert the numbers to an integer or float type before calling min/max.

# under n >= 0:
num = int(num) # or num = float(num)
num_list.append(num)

so an example of working code would be:

num_list = []
while True:
   num = raw_input("Enter a number: ")
   if num == "done" :
       break
   try: # use a try except to verify user input is in fact a number
       num = int(num) + 0 # alternatively use float(num) if non integer numerical inputs will be used
       if num >= 0:
           num_list.append(num)
           print "min: ",min(num_list)
           print "max: ",max(num_list)
   except:
       print "invalid input"

Not calling max/min every iteration:

num_list = []
_min, _max = None, None
while True:
    num = raw_input("Enter a number: ")
    if num == "done" :
        break
    try: # use a try except to verify user input is in fact a number
        num = int(num) # alternatively use float(num) if non integer numerical inputs will be used
        if num >= 0:
            if not _min or not _max:
                _min,_max = num, num
            elif num < _min:
                _min = num
            elif num > _max:
                _max = num

            num_list.append(num)

   except:
       print "invalid input"

   print "min:", _min
   print "max:", _max
nick
  • 1,197
  • 11
  • 16