Search code examples
pythonregexpython-2.7raw-input

How to match a string in python with conditional looping


I am a beginner in python. I want to ask the user to input his first name. The name should only contain letters A-Z,if not, I want to display an error and request the user to enter the name again until the name is correct. Here is the code am trying. However, The string is not checked even when it contains numbers and special characters. Where am I going wrong??

def get_first_name():
try_again = True
while(try_again==True):
    first_name = raw_input("Please enter your first name.")
    if (re.match("^[A-Za-z]+$", first_name)==False):
        try_again = True
    else:
        try_again = False
        return first_name

Solution

  • You don't need re, just use str.isalpha

    def get_first_name():  
         while True:
            first_name = raw_input("Please enter your first name.")
            if not first_name.isalpha(): # if not all letters, ask for input again
                print "Invalid entry"
                continue
            else: # else all is good, return first_name
                return first_name
    In [12]: "foo".isalpha()
    Out[12]: True
    
    In [13]: "foo1".isalpha()
    Out[13]: False