Joe han
Joe han

Reputation: 171

how to loop through the user defined function?

I have this program:

word = input('Customer Name: ')
def validateCustomerName(word):
    while True:
        if all(x.isalpha() or x.isspace() for x in word):
            return True

        else:
            print('invalid name')
            return False

validateCustomerName(word)

I want the program to repeat to ask the user to input their name if their name is entered wrongly such as if it has numbered in it. Return True if the name is valid and False for invalid

output:

Customer Name: joe 123
invalid name

expected output:

Customer Name: joe 123
invalid name
Customer Name: joe han
>>>

Am I missing something in the program?...Thanks

Upvotes: 0

Views: 1776

Answers (2)

Gadi
Gadi

Reputation: 21

This should serve your purpose:

def validateCustomerName(word):
    while True:
        if all(x.isalpha() or x.isspace() for x in word):
            return True
        else:
            print('invalid name')
            return False

while (True):
   word = input('Customer Name: ')
   status = validateCustomerName(word)
   if status: 
       print ("Status is:",status)
       break

Upvotes: 1

Andrew Guy
Andrew Guy

Reputation: 10008

Any return statement from within a function definition will exit the enclosing function, returning the (optional) return value.

With that in mind, you could refactor to something like:

def validateCustomerName(word):
    if all(x.isalpha() or x.isspace() for x in word):
        return True
    else:
        print('invalid name')
        return False

while True:
    word = input('Customer Name: ')
    if validateCustomerName(word):
        break

Upvotes: 1

Related Questions