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

JavaScript

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