Skip to content
Advertisement

How to only count valid inputs

I have a function that is supposed to take input, calculate the average and total as well as record count.

The bug in the code is that:

Even though I have added a try and except to catch errors, these errors are also being added to the count. How do I only count the integer inputs without making the “Invalid Input” part of the count?

Code snippet

count = 0
total = 0
avg = 0
#wrap entire function in while loop
while True:
    #prompt user for input
    line = input('Enter a number: ')
    try:
        if line == 'done':
            break
        print(line)
        #function formulars for total, count, avg
        count = int(count) + 1
        total = total + int(line)
        avg = total / count
    except:
        print('Invalid input')
        continue
#print function results
print(total, count, avg)

With the above code the output for print(total, count, avg) for input i.e 5,4,7, bla bla car, done :

  • will be 16, 4, 5.33333333

  • expected output 16, 3, 5.33333333

Advertisement

Answer

When this line: total = total + int(line) throws an error,

The previous line count = int(count) + 1 has already ben executed, which incremented the count.

Swapping these two line should solve the problem.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement