I want a way for the user not to make an integer input by using this function:
x = input("Whats your name?")
while x == int:
y = input("why is there a number in your name? Please re enter your name")
But this does not work. Any idea why?
I want a way for the user not to make an integer input by using this function:
x = input("Whats your name?")
while x == int:
y = input("why is there a number in your name? Please re enter your name")
But this does not work. Any idea why?
Improving in @persian_dev's answer -
def check_name(string):
for char in string :
try:
int(char)
return False
except:
continue
return True
This will traverse the string, try to convert each character to int and return False on first success in doing so.
The input function will convert anything user enters to a string.
So you want to instead look whether there is any number contained in x, rather than the type.
See here: check if a string contains a number
here is a check function :
def isnumeric(string):
try:
int(string)
return True
except:
return False
def check_name(string):
for char in string:
if isnumeric(char):
return False
return True
If you just want to make sure the user input contains strings only, you can use isalpha()
to check the input:
x = raw_input("Whats your name?")
while not x.isalpha():
x = raw_input("why is there a number in your name? Please re enter your name")
I use Python 2 so I used raw_input
instead of input
. If you use Python 3 you can adjust accordingly.
int
is a type. You're not asking "Does x contain a number?" or even "Is x a number?", you're asking "Is x number?" (integer, more precisely). Makes no sense. Assuming entering names work, you're using Python 3, in which case the result of input
is always a string. Even if it's a string of only digits. So isinstance(x, int)
won't work, either. You could try casting with int(...)
, but that won't help if the name contains a number only somewhere among letters.
Here's a good way to test whether there's any digit in a string:
any(map(str.isdigit, x))
In your code, also with the y
corrected to x
:
x = input("Whats your name? ")
while any(map(str.isdigit, x)):
x = input("why is there a number in your name? Please re enter your name ")