'How to Input numbers in python until certain string is entered

I am completing questions from a python book when I came across this question.

Write a program which repeatedly reads numbers until the user enters "done". Once done is entered, print out total, count, and average of the numbers.

My issue here is that I do not know how to check if a user specifically entered the string 'done' while the computer is explicitly checking for numbers. Here is how I approached the problem instead.

#Avg, Sum, and count program

total = 0
count = 0
avg = 0
num = None

# Ask user to input number, if number is 0 print calculations
while (num != 0):
    try:
        num = float(input('(Enter \'0\' when complete.) Enter num: '))
    except:
        print('Error, invalid input.')
        continue

    count = count + 1
    total = total + num

avg = total / count
print('Average: ' + str(avg) + '\nCount: ' + str(count) + '\nTotal: ' + str(total))

Instead of doing what it asked for, let the user enter 'done' to complete the program, I used an integer (0) to see if the user was done inputting numbers.



Solution 1:[1]

Keeping your Try-Except approach, you can simply check if the string that user inputs is done without converting to float, and break the while loop. Also, it's always better to specify the error you want to catch. ValueError in this case.

while True:
    num = input('(Enter \'done\' when complete.) Enter num: ')
    if num == 'done':
        break
    try:
        num = float(num)
    except ValueError:
        print('Error, invalid input.')
        continue

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Keyur Potdar