如果我首先输入有效的数据,它可以正常工作,但如果我输入无效数据,则返回有效数据,无。以下是问题的一个示例:
代码:
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)
答案 0 :(得分:2)
您的问题是您没有正确使用递归。以不匹配密码为例:hello
和hello1
。
在if passwordMatch(password, password2):
之前,您的功能将会正常。此时,passwordMatch
返回None
。这是因为在passwordMatch
中您没有说return enterPasswords()
,因此返回值默认为None
,而不是enterPasswords
新调用的返回值。
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 :(得分:1)
所以会发生的情况是,如果您首先输入无效数据(假设密码长度无效),则再次从passwordLength()函数调用enterPasswords()。这会提示您输入另一个密码。这次输入有效输入。您可以到达应该返回密码的位置,然后将其返回。问题是,在堆栈上,您将返回到您从passwordLength()函数调用enterPasswords()的位置。这是您返回有效密码的地方。它没有对它做任何事情,执行返回到对inputPasswords()的原始调用(输入无效),你将从那里返回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