2017-10-16 58 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

工作作爲呃...以及地位......謝謝 –