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
x
21
21
1
count = 0
2
total = 0
3
avg = 0
4
#wrap entire function in while loop
5
while True:
6
#prompt user for input
7
line = input('Enter a number: ')
8
try:
9
if line == 'done':
10
break
11
print(line)
12
#function formulars for total, count, avg
13
count = int(count) + 1
14
total = total + int(line)
15
avg = total / count
16
except:
17
print('Invalid input')
18
continue
19
#print function results
20
print(total, count, avg)
21
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.