2017-10-16 57 views
0

我有这个程序:如何循环通过用户定义的函数?

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) 

我希望程序反复要求用户输入他们的名字,如果输入自己的名字说错了,例如,如果它在它已经屈指可数。 返回如果该名称是无效

输出有效和False:

Customer Name: joe 123 
invalid name 

预期输出:

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

我缺少的东西方案...谢谢

+0

[询问用户进行输入的可能的复制,直到他们得到一个有效响应](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – SiHa

回答

1

函数定义中的任何return语句都将退出封闭函数,并返回(可选)返回值。

考虑到这一点,你可以重构的东西,如:

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 
+0

yup ...它的工作原理...谢谢 –

1

这应该成为你的目的:

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 
+0

工作作为呃...以及地位......谢谢 –