Search code examples
pythonexceptioninputerror-handlingdata-conversion

A python program that reads numbers and stops when you enter 'done' using try and except


I tried writing a program that reads numbers using a loop, evaluates the total numbers, prints it and stops when you type done using try and except.

initiator = True
myList = []

while initiator:
    try:
        userIn = int(input('Enter any number >>  '))
        myList.append(userIn)
        print(myList)

    except ValueError:
        if str(userIn):
            if userIn == 'done':
                pass
            average = eval(myList)
            print(average)
            initiator = False

        else:
            print('Wrong input!\nPlease try again')
            continue

Solution

  • When int() raises an exception, it doesn't set userIn, so you can't compare userIn with done.

    You should separate reading the input and callint int().

    while True:
        try:
            userIn = input('Enter any number >>  ')
            num = int(userIn)
            myList.append(num)
            print(myList)
    
        except ValueError:
            if userIn == 'done':
                break
            else:
                print('Wrong input!\nPlease try again')
    
    average = sum(myList) / len(myList)
    print(average)
    

    eval() is not the correct way to get the average of a list. Use sum() to add up the list elements, and divide by the length to get the average.