1

I am a beginner of Python and using PyCharm for an exercise.

After inputting the following code:

promotion_percentage = int(input('Enter a integer from 1 to 100: '))

An error is then produced:

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

I read quite a lot of Q&A in the forum. But their cases look more complicated than mine.

Where the error comes from?

1 Answer 1

1

You're trying to convert something which isn't an integer. I can reproduce the problem when I type in any alpha character.

An easier way to see what is going on would be to make the input it's own variable and step through the debugger.

Try something like this and see what get's printed before the assert.

var = input('Enter a integer from 1 to 100: ')
print(repr(var), type(var))
assert var.isalnum(), "var should be only numbers"
promotion_percentage = int(var)
print(promotion_percentage, type(promotion_percentage))

Notice that when I type in only numbers, your code works.

Enter a integer from 1 to 100: 234
'234' <class 'str'>
234 <class 'int'>

but when I give it a non-integer...

Enter a integer from 1 to 100: abc
'abc' <class 'str'>
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: 'abc'

To explain the error you are specifically getting, your input is an empty string. This happens when you hit enter without typing anything. In which case I would follow the advice from this post.

var = input('Enter a integer from 1 to 100: ')
print(repr(var), type(var))
assert var.isalnum(), "var should be only numbers"
if not var:
    # ask them again?
    # exit script?
    # set a default value?
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Marcel. The problem has been solved!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.