2013-04-03 71 views
0

如果我第一次輸入有效的數據,它可以正常工作,但如果我輸入無效數據,則返回有效數據,無。這是問題的一個例子:這個函數爲什麼沒有返回?

screenshot

代碼:

def passwordLength(password): 
    if (len(password) < 4) or (len(password) > 15): 
     print("Error from server: Your password must be at least four and at most fifteen characters long.") 
     enterPasswords() 
    else: 
     return True 


def passwordMatch(password, password2): 
    if password != password2: 
     print("Error from server: Your passwords don't match.") 
     enterPasswords() 
    else: 
     return True 

def enterPasswords(): 
    password = input("Message from server: Please enter your desired password: ") 
    if passwordLength(password): 
     password2 = input("Message from server: Please re-enter your password: ") 
     print(password, password2) 
     if passwordMatch(password, password2): 
      print(password) 
      return password 

password = enterPasswords() 
print(password) 
+1

如果控制到達函數不返回任何月底,'None'默認情況下返回。 – 2013-04-03 19:11:31

+0

它適用於我...它返回從鍵盤讀取的內容 – 2013-04-03 19:16:16

回答

2

你的問題是,你不使用遞歸正常。以不匹配的密碼爲例:hellohello1

你的功能會很好,直到if passwordMatch(password, password2):。此時,passwordMatch返回None。這是因爲在passwordMatch中,您不會說return enterPasswords(),所以返回值默認爲None,而不是新呼叫的返回值爲。

if password != password2: 
     print("Error from server: Your passwords don't match.") 
     enterPasswords() # Doesn't return anything, so it defaults to None 

如果你要使用這樣的功能,那麼你不會有問題。

def passwordMatch(password, password2): 
    if password != password2: 
     print("Error from server: Your passwords don't match.") 
     return enterPasswords() 
    else: 
     return True 

請注意,您在passwordLength中遇到同樣的問題。

1

因此,如果您首先輸入無效數據(假設密碼長度無效),您將再次從passwordLength()函數中調用enterPasswords()。這會提示你輸入另一個密碼。這次您輸入有效的輸入。你可以回到你應該返回密碼的地方,然後返回。問題是,在堆棧中,您將返回您從passwordLength()函數調用enterPasswords()的位置。那就是你要返回有效密碼的地方。它沒有做任何事情,執行返回到最初調用enterPasswords()(輸入無效),並且你將從那裏返回None。

的可視化:

enterPasswords() called 

    prompted for input, give string of length 3 

    passwordLength(password) called 

     Invalid string length, print an error and then call enterPasswords() 

      prompted for input, give valid string 

      passwordLength(password) called 

       valid length, return true 

      prompted for input for second password 

      passwordMatch(password, password2) called 

       passwords match, return True 

      print password 

      return password to the first passwordLength() call 

     nothing else to do here, pop the stack and return to the first enterPasswords() 

    nothing else to do here, pop the stack 

print(password), but password is None here