Home > front end >  Two identical while loops giving different results
Two identical while loops giving different results

Time:08-24

I am trying to write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number. I used two methods that are supposed to give the same result, but for some reason they give different outcomes...thanks for all your help!

First one:

lst = list()
largest = None
smallest = None
count = 0 
total = 0 

while True: 
  number = input('Enter a number ')
  if number == 'done': 
    print(largest, smallest, count, total, total/count)
    break
  try:
    number = float(number)
    lst.append(number)
    for num in lst:
      count  = 1
      total = total   num 
      if largest == None or largest < num:
        largest = num
      if smallest == None or smallest > num:
        smallest = num 
      break
  except:
    continue
    print('Invalid input ')

Second one:

lst2 = list()

while True:
  val = input('Enter a number ')
  if val == 'done': 
    print(len(lst2), sum(lst2), sum(lst2)/len(lst2), max(lst2), min(lst2)
    break
  try:
    val = float(val)
    lst2.append(val)
  except:
    continue
    print('Invalid input ')

CodePudding user response:

If I can make a few suggestions:

Move the max and min computations outside of the while loop, catch for specific exceptions, I don't know if it is considered bad practice to not just let the code fall out of the loop or if breaking out is actually "okay" or proper in python, but you can simply change the loop's condition to be contingent on a variable that is set to true, then set it to false when you are ready to leave the loop. You were also breaking out of the loop that computed the values too early.

Original with comments:

lst = list()
largest = None
smallest = None
count = 0 
total = 0 

while True: 
    number = input('Enter a number ')
    if number == 'done': 
        # move this outside of the while loop, below the code in the try block
        print(largest, smallest, count, total, total/count)
        break
    try:
        number = float(number)
        lst.append(number)
        # move this outside of the while loop
        for num in lst:
            count  = 1
            total = total   num 
            if largest == None or largest < num:
                largest = num
            if smallest == None or smallest > num:
                smallest = num 
            # the loop only gets executed once...
            break
    except ValueError:
    #except:
        continue
        print('Invalid input ')

Changes with more comments:

lst = list()
largest = None
smallest = None
count = 0 
total = 0 
while_true = True

while while_true: 
    number = input('Enter a number ')
    if number == 'done':
        while_true = False
    try:
        number = float(number)
        lst.append(number)
    except ValueError:
        continue
        print('Invalid input ')
for num in lst:
    count  = 1
    # you can use the same syntactic sugar -> total  = num
    total = total   num 
    if largest == None or largest < num:
        largest = num
    if smallest == None or smallest > num:
        smallest = num
if count == 0:
    count = 1
# since you initiate count to 0 - if the user just types done with no numbers,
# you could get a division by 0 error when you go to print "total / count",
#so you need to do something with it or catch the error.
print(largest, smallest, count, total, total/count)

Please use proper indentation:

lst2 = list()

while True:
    val = input('Enter a number ')
    if val == 'done': 
        print(len(lst2), sum(lst2), sum(lst2)/len(lst2), max(lst2), min(lst2)
        break
    try:
        val = float(val)
        lst2.append(val)
    except ValueError:
        continue
        print('Invalid input ')

CodePudding user response:

In the first code example, it breaks out of the for loop after only one iteration, so the total is getting the first value added to it each time a new number is added, instead of the new value. The logic for count and total probably doesn't belong in the for loop anyway, as that's done each time a new number is added, and only needs to be done once. I would move that up to the if number == 'done': block.

CodePudding user response:

Using for num in list: and break you always work with first value on list - list[0] - and you get something like total = list[0] list[0] list[0] ... and you always compare largest < list[0] and smallest > list[0]. If you would use print() to see what you really have in variables then you would see this problem.

You should use directly number without for-loop and without list

largest = None
smallest = None
count = 0 
total = 0 

while True: 
  number = input('Enter a number ')
  if number == 'done': 
    print(largest, smallest, count, total, total/count)
    break
  try:
    number = float(number)
    count  = 1
    total  = number
    if largest == None or largest < number:
        largest = number
    if smallest == None or smallest > number:
        smallest = number
  except:
    print('Invalid input')

CodePudding user response:

lst = list()
largest = None
smallest = None
count = 0
total = 0

while True:
  number = input('Enter a number ')
  if number == 'done':
    print(count, total, total/count, largest, smallest)
    break
  try:
    number = float(number)
    lst.append(number)
    count  = 1
    total = total   number
    if largest == None or largest < number:
      largest = number
    if smallest == None or smallest > number:
      smallest = number
  except:
    print('Invalid input ')
    continue
  • Related