0

I have been trying to simply turn an input() function into an integer as the title of this question suggests. I am essentially trying to run a program that takes in as many inputs as the user inputs, but when an empty string is inputted, it breaks out of a loop and returns the average of all inputted numbers. Currently, my code looks like this:

count = 0
sum = 0.0
number = 1.0

while number != 0:
    number = int(input(""))
    sum = sum + number
    count += 1
    if number == 0:
        continue
    if number == "":
        break
else:
    print("Average is {}".format(sum / (count-1)))

The issue i face is the error:

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

Does anyone have a simple solution for this? I feel like i'm overlooking something rather simple?

  • 2
    You have to check for the user's input being `""` *before* you call `int()` on it. – jasonharper Jun 06 '20 at 02:08
  • Your edit just changed `input()` to `input("")` - that's just the prompt shown to the user, which defaults to an empty string anyway. This has *nothing* to do with the problem. – jasonharper Jun 06 '20 at 02:13

1 Answers1

0
if number == "":
    break

In the case where you want this to happen, number got its value as int(input()). That is, the attempt to convert to int happens first. Since an empty string cannot be converted to int, this test is not reached before the exception is thrown.

You should test for the exception anyway, using try:/except:. But if you want to compare a string to a string, you need to do it at the point where you still have the strings you want to do the comparison with.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153