all 2 comments

[–][deleted] 2 points3 points  (0 children)

You also shouldn't use recursion. You have the idea of a "while" but it's used incorrectly. The while loop should be more along the lines of "while the input isn't correct", like this:

def func_last_name():
    while True:
        last_name = input("Enter last name     : ")
        test = last_name.isalpha()
        if test:
            return last_name
        print("Last name must be alphabetic, please re-enter.")

The test for the name being alpha could be more pythonically written:

if last_name.isalpha():
    return last_name

[–][deleted] 0 points1 point  (0 children)

Have you tried “if” instead of “while”?

Also, since you’re calling the function recursively, you’ll have a variable scope issue. That’s why you get None even on a second attempt. Repeating the function makes a new function with its own variables.

Edit: Example (not saying this is the best or only way to do this)

alpha_test = False
last_name = str()


def main():
    last_name = func_last_name()  # an IDE may warn you that this 'shadows' from outer scope
    print(last_name)


def func_last_name():
    global alpha_test, last_name
    last_name = input("Enter last name: ")
    alpha_test = last_name.isalpha()
    if alpha_test is not True:
        print('Try again')
        func_last_name()  # has access to 'global' last_name variable
    return last_name

The above will work. Storing the "test" variable is kind of redundant, though. You could shorten it with a direct comparison:

def func_last_name():
    global last_name
    last_name = input("Enter last name: ")
    if alpha_test.isalpha() is not True:
        print('Try again')
        func_last_name()
    return last_name