0

如果我首先输入有效的数据,它可以正常工作,但如果我输入无效数据,然后是有效数据,则返回 None。这是问题的一个例子:

截屏

代码:

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)
4

2 回答 2

2

您的问题是您没有正确使用递归。以不匹配密码为例:hellohello1.

你的功能会很好,直到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.

于 2013-04-03T19:17:02.400 回答
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
于 2013-04-03T19:56:28.430 回答