How do I take input in Python from a user?
Does the Python input function always return a string?
What are input parameters in Python?
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
input() always returns a string, so you can try these methods:
METHOD 1. Use isalpha(). It checks if all characters are alphabetical, but does not allow for spaces.
name = input('Please enter your name: ')
if name.isalpha() == False:
print('Please enter a alphabetical name')
To allow spaces in a name (for example, first and last name), do this:
name = input('Please enter your name: ')
nospacename = name.replace(' ','')
if nospacename.isalpha() == False:
print('Please enter a alphabetical name')
This does not change the value of name, however.
METHOD 2. Try to convert it to a integer or float, and print the message if it is possible. Otherwise, do nothing.
name = input('Please enter your name: ')
try:
intname = int(name)
floatname = float(name)
print('Please enter an alphabetical name.')
except:
pass
METHOD 3. Go through the name, character by character, and check if it is a type int (integer) or float.
name = input('Please enter your name: ')
namelist = list(name)
invalid = 0
for i in range(len(name)):
if type(namelist[i]) == int:
invalid = invalid + 1
elif type(namelist[i]) == float:
invalid = invalid + 1
else:
pass
if invalid > 0:
print('Please enter a alphabetical name.')