Search code examples
pythonstringpython-3.xinputerror-handling

Prevent input() from being anything but alphabet characters


I am attempting to make a program for the sake of self-knowledge. I want to ask the user what their name is, and I only want the user to be able to use letters from the alphabet to answer, or only strings. I do not want them to be able to answer with numbers, symbols, etc.

def cc():
  name = (input("""Hello, what happens to be your first name?  
        > """))
  if type(name) is str:
      print("You have entered a name correctly.")
  elif type(name) is int:
      print("Your name cannot be an integer. Try again.")
      cc()

cc()

Solution

  • You can enforce this requirement using str.isalpha. From the documentation:

    Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.

    Here is an example program:

    while True:
        name = input('Enter a name using only alphabetic characters: ')
        if name.isalpha():
            break
    

    Demo:

    Enter name using only alphabetic characters:  Bo2
    Enter name using only alphabetic characters:  Bo^&*(
    Enter name using only alphabetic characters:  Bob
    

    Note this method will not work for people with hyphenated names such as "Anne-Marie".