1

我在编写的程序中遇到了一个问题。我已将问题缩小到这两个功能。当您调用函数 enterPasswords,输入无效数据(例如“a”),然后通过输入有效数据(例如“hello”)退出 passwordLength 函数时,就会出现问题。我在那里留下了一些打印语句来帮助您查看问题。我试过添加退货,但同样的问题仍然存在。

任何建议将不胜感激。如果你能告诉我为什么会出现问题,我相信我可以自己解决。谢谢。

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


    def enterPasswords():
        password = input("Input password: ")
        passwordLength(password)
        print(password)
        password2 = input("Re-enter password: ")
        print(password, password2)


    enterPasswords()

这是我的问题的图像(我想知道的是,为什么程序没有在我突出显示的地方结束,为什么会继续进行,为什么最后会打印“a”?):

http://i.imgur.com/LEXQFTO.png

4

3 回答 3

4

看起来,如果用户首先输入了无效密码,它会重复enterPasswords- 但是,如果用户成功完成此操作,它会回到最初的enterPasswords. 相反,尝试

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.")
        return False
    return True


def enterPasswords():
    password = input("Input password: ")
    while not passwordLength(password):
        password = input("Input password: ")

    print(password)
    password2 = input("Re-enter password: ")
    print(password, password2)

这将继续要求用户重新输入第一个密码,直到它有效,然后才会要求用户确认。

于 2013-04-03T14:09:03.343 回答
0

密码变量 in 与变量 inpasswordLength()完全无关enterPasswords()。行为也可能与您预期的不同。尝试这样的事情:

def passwordLength(pw):
    return 4 <= len(pw) <=15

def getPw():
    return input("Enter password: ")

def enterPasswords():
    pw = getPw()
    while not passwordLength(pw):
        print("Incorrect password length.")
        pw = getPw()

    # ...
于 2013-04-03T14:13:54.333 回答
0

您的函数以一种糟糕的方式相互调用。如果您尝试逐行遵循您的算法(使用您提到的“a”和“hello”的情况),您可能会看到问题。

这是一个解决方案:

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.")
        return False
    else : return True    


def enterPasswords(): 
    passwordOK = False
    while not passwordOK :
        password = input("Input password: ")
        passwordOK = passwordLength(password)
    print(password)
    password2 = input("Re-enter password: ")
    print(password, password2)

enterPasswords()
于 2013-04-03T14:31:32.397 回答