Home > Blockchain >  How to only count valid inputs
How to only count valid inputs

Time:12-31

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:

Eventhough 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

CodePudding user response:

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.

CodePudding user response:

The reason why you have another count is because you added a count because you put 'done', which doesn't raise an error, so you can just do (before the print statement):

... # code before

count -= 1

print(total, count, avg)

CodePudding user response:

Add line = int(line) before count = int(count) 1 so the exception will be catched before count evaluated, or swap it with total:

count = 0
total = 0
avg = 0
while (line := input('Enter a number: ')) != 'done':
    try:
        # line = int(line)
        total  = int(line)
        count  = 1
        avg = total / count
    except ValueError:
        print('Invalid input')

print(total, count, avg)

# Enter a number: 5
# Enter a number: 4
# Enter a number: r
# Invalid input
# Enter a number: 7
# Enter a number: done
# 16 3 5.333333333333333
  • Related