Using Exception Handling in Python

Question:

Using exception handling inside a loop in python, I’m receiving inputs from a user and adds it to a list but if the user types ‘done’ the loop terminates and sums up the list. If the user types any other non numeric data it would print ‘Wrong Data’ and continue the loop. My issues are: Adding the list. Converting the user data from number to string. Reading a string data first from the user. And terminating the loop with ‘done’.

total = 0
user_list = []


while True:
    try:
        user_entry = int(input('('done' is your terminator.)nEnter any number only! >>  '))
        user_list.append(user_entry)
        total = total + user_list
    except ValueError:
        if str(user_entry) == 'done':
            break
        else:
            print('Wrong Data')
            continue

Asked By: Kimm Muna

||

Answers:

There’s lots of code in the try block that should go before or after the try statement.

total = 0
user_list = []

while True:
    user_entry = input('('done' is your terminator.)nEnter any number only! >>  ')

    if user_entry == 'done':
        break

    try:
        user_entry = int(user_entry)
    except ValueError:
        print('Wrong Data')
        continue

    user_list.append(user_entry)
    total += user_entry

Note that instead of keeping running total, you can simply wait until after the loop to call total = sum(user_list).

Answered By: chepner