简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM