-1

I'm new to python. In this code, I'm trying to ask for numbers repeatedly. When the user enters 0, the program print the average of the numbers exclude 0. I can get the average from this code. However, there's a ValueError,

y = int(input())
ValueError: invalid literal for int() with base 10: ''

I don't understand why this error happens. Is it because of convert variable type under while loop? Can anyone help? Thanks!!

nums=0
i=0
x = int(input())
while x>0:
    y = int(input())
    i = i + 1
    nums = y + nums
    if y == 0:
        avg = (nums+x)/(i)
        print("The average of those numbers is {:.2f}.".format(avg))
2
  • 6
    What are the series of inputs which cause this error? Sep 12, 2020 at 13:06
  • Welcome to SO! From the error message, I would deduce that you are typing an extra enter that would be treated as an empty string by the input function in the while loop Sep 12, 2020 at 13:08

4 Answers 4

2

This error occurs when you try to input a string of characters, instead of numbers.

E.g:

if you input '', 'string' - These won't work
but if you input '9', '239412' - This will work
0

It is likely the line y = int(input()) is receiving a string from the user input .
See this example.

>>> while True:
...  y = int(input())
...  print "Y=",y
...
12
Y= 12
0
Y= 0
"this"
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'this'
0

Like @Blade said you should give numbers as input. You can do this:

nums=0
i=0
try:
    x = int(input())
    while x>0:
        try:
            y = int(input())
            i = i + 1
            nums = y + nums
            if y == 0:
                avg = (nums+x)/(i)
                print("The average of those numbers is {:.2f}.".format(avg))
        except:
            print("Input is not a number")
        
except:
    print("Input is not a number")
0

You got the Value Error because you entered a space( "") which considered as a string but the input should be an integer int For calculating the average of two numbers you can use this simple code instead : -

def average(x, y):
    " Returns the average of two numbers "
    return (x+y)/2


x = int(input("Enter a number:\n"))
y = int(input("Enter another number :\n"))
print(average(x, y))

Not the answer you're looking for? Browse other questions tagged or ask your own question.