0

My code needs to validate user input to make sure they enter a number and keep looping until they enter a number.

My code:

user_input=input("Enter a number: ")
while user_input != int:
    user_input=input("Error: Enter a number: ")

My Output:

Enter a number: d

Error: Enter a number: f

Error: Enter a number: 5

Error: Enter a number: 5

Error: Enter a number: 3

Why doesnt it even accept numbers?

1
  • May be all you want is user_input.isnumeric() Commented Mar 20, 2017 at 0:50

1 Answer 1

1

Answer

I think the piece of code below solves your problem in a way that is easily understood.

user_input = input("Enter a number: ")
while not user_input.isnumeric():
    user_input = input("Error: Enter a number: ")

Explanation

The code you have didn't work because of while user_input != int.

When you call the input function, and the user provides an input, that input is always a string.

>>> num = input('Enter a number: ') # 5, as a string
>>> num
'5'

Your intent is to check if num is a number. So, to check if a string represents some number, you can use the str.isdigit(), str.isdecimal(), and str.isnumeric() methods. You can read more here.

It's easy to mistakenly believe the following approach is viable, but it can quickly get messy.

while not isinstance(user_input, int):

Remember, the input you receive as a result of calling the input function will be a string. Therefore, the code above will always be True, which is not what you want. Though, the code above could work if you change user_input to be of type int.

>>> num = input('Enter a number: ') # 5, as a string
>>> num
'5'
>>> int(num)
5
>>> isinstance(num, int)
True

But the interpreter would throw an error if num was something else.

>>> num = input('Enter a number: ') # 'A'
>>> int(num)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'A'

This brings us back to the answer, which involves using a string method to check if the string represents some number. I chose to use the str.isnumeric() method because it is the most flexible.

I hope this answers your question. Happy coding!

Sign up to request clarification or add additional context in comments.

Comments

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.