0

If i need the user to input a number in python, how can i check if they really did enter the number and not a string???

variable = int(input("Enter your age? ")), to actually make sure the 'variable' in this case stores a number and not a string or an empty string, without giving an error, "ValueError: invalid literal for int() with base 10: ' ' "...

4th Mar 2022, 12:07 PM
Chris
3 Antworten
+ 3
The ValueError is actually there for you to catch ;) If the error is raised (risen?) then the input was not a valid number. And that, I believe, is precisely the information you are looking for :) try: i = int(input()) except ValueError: # handle invalid input here # for example setting a default # continue normal processing here
4th Mar 2022, 12:10 PM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 2
You can use the "isnumeric" function. You can do something like the below snippet, variable=input("Enter your age:") if(variable.isnumeric()): num=int(variable) else: print("Enter a number pls")
4th Mar 2022, 12:12 PM
Rishi
Rishi - avatar
+ 1
Hi Chris! You may find the isdigit() method useful in this case. It returns true if all the characters of that variable are integers and false vice versa. Here's how you do it if input_var.isdigit(): #the rest else: #error message
4th Mar 2022, 12:13 PM
Python Learner
Python Learner - avatar