If you're using Python 3.X, input()
always returns a string. Note that there are strings such as "1"
, which are still strings, despite the fact that they look a lot like numbers.
I think what you actually want is to verify that a string contains only alphabetical characters, in which case you could do:
s = input("Enter your name: ")
if not s.isalpha():
print("Please enter only alphabetical characters for your name.")
Or perhaps you want to accept all strings except ones that are composed solely of digits.
s = input("Enter your name: ")
if s.isdigit():
print("Your name cannot be a number.")
Or do you want to accept only strings that don't contain any digits at all?
s = input("Enter your name: ")
if any(char.isdigit() for char in s):
print("Please do not include digits in your name.")
If you're using Python 2.7 or lower, input()
can return a string, or an integer, or any other type of object. This is generally more of a headache than it's worth, so I recommend switching to raw_input()
, at which point all of the advice above applies.
Once you've got the right logic for your validation conditions, you might think "ok, but how do I get the program to go back to the first input()
call so the user gets another chance to enter the right input?". If so, you may find this useful: Asking the user for input until they give a valid response
PS. When it comes to names, be careful about how strictly you validate input. Err on the side of accepting unusual inputs. Otherwise you might get complaints from people with names like "John Smith the 3rd" or "Steve O'Reilley" or "田中太郎". Related reading: Falsehoods Programmers Believe About Names