Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using Exception Handling in Python

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading