0

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.

Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
jermhern
  • 110
  • 1
  • 2
  • 10

2 Answers2

2

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
Keyur Potdar
  • 7,158
  • 6
  • 25
  • 40
1

I think a better approach that would solve your problem would be as following :

input_str = input('(Enter \'0\' when complete.) Enter num: ')
if (input_str.isdigit()):
    num = float(input_str)
else:
    if (input_str == "done"):
        done()
    else:
        error()

This way you control cases in which a digit was entered and the cases in which a string was entered (Not via a try/except scheme).

Rohi
  • 814
  • 1
  • 9
  • 26
  • 1
    try-except is always preferred over if-else in Python. See [the EAFP principle in Python](https://stackoverflow.com/questions/11360858/what-is-the-eafp-principle-in-python). – Keyur Potdar Mar 26 '18 at 05:57
  • I can agree its better to be safe then sorry but in this specific case, you lose 'control' over the analyzing of the input when using the try/except scheme. – Rohi Mar 26 '18 at 05:59
  • @Rohi Thank you very much for your help =) .isdigit() is very powerful – jermhern Mar 26 '18 at 06:03
  • @Rohi, it shouldn't matter much, but, I've added my answer showing how to use EAFP principle for this question. – Keyur Potdar Mar 26 '18 at 06:19