繁体   English   中英

我该如何修复while循环

[英]How do i fix my while loop

我正在编写一个程序,要求用户输入密码。 如果密码与我设置的常数匹配,则会打印出“成功登录消息”。 但是,如果密码不正确,则会给出剩余的猜测数,并要求用户重试。 该程序应该在3次错误的猜测之后结束,但是即使使用了3次尝试,它仍会继续询问。 我认为问题出在我的while循环中,但我不确定。

码:

def main():
    PASSWORD = "apple"
    ALLOWED = 3

    password = input("Enter the password: ")
    while password != PASSWORD :
        ALLOWED = ALLOWED - 1
        print("Wrong. You have", ALLOWED, "guesses left")

        if ALLOWED == 0:
                    print("You have been locked out")
        password = input("Enter again ")            


    print("You have successfully logged into the system")



main()

现在,您永远不会退出while循环。 要打破它,请使用break关键字。 要完全退出程序,您将需要import syssys.exit()我建议将它们添加到if ALLOWED == 0语句中。

您需要使用break退出循环,或添加一个辅助条件,否则它将继续进行直到密码正确为止。

因此,要么:

while (password != PASSWORD) and (ALLOWED > 0):

要么:

    if ALLOWED == 0:
                print("You have been locked out")
                break

条件密码!= PASSWORD不足以退出循环(只有输入正确的密码,它才会退出循环)。 同时在while中添加条件(密码!= PASSWORD,并且允许> 0)

print("You have been locked out")更改为sys.exit("You have been locked out") (否则退出main )。 记住要import sys以使用sys.exit

您的while循环需要输入正确的密码才能完成,并且没有其他方法可以退出循环。 我建议一个中断声明:

def main():
    PASSWORD = "apple"
    ALLOWED = 3

    password = input("Enter the password: ")
    while password != PASSWORD :
        ALLOWED = ALLOWED - 1
        print("Wrong. You have", ALLOWED, "guesses left")

        if ALLOWED == 0:
            print("You have been locked out")
            break
        password = input("Enter again ")

    print("You have successfully logged into the system")

如果您的程序需要安全,则可能需要做更多研究。

设法使其工作,但只是使其检查是否ALLOWED == 0,并且是否确实打印“您被锁定”,并且如果ALLOWED <= 0,则它不会让您走得更远。

def main():
    PASSWORD = "apple"
    ALLOWED = 3

    password = input("Enter the password: ")
    while password != PASSWORD or ALLOWED <= 0:
        ALLOWED = ALLOWED - 1
        if ALLOWED > 0: print("Wrong. You have", ALLOWED, "guesses left")
        if ALLOWED == 0: print("You have been locked out") 
        if ALLOWED < 0:
                    print("You have been locked out")
        password = input("Enter again ")            


    print("You have successfully logged into the system")



main()

还写了一个不同的版本,我认为这似乎更容易

def main():

    USERNAME = "admin"
    PASSWORD = "root"
    ATTEMPTS = 3
    while ATTEMPTS >= 1:
        print("You have",ATTEMPTS,"attempts left")
        if ATTEMPTS == 0:
            break
        user = input("Please enter your username:")
        password = input("Now enter your password:")
        if user == USERNAME and password == PASSWORD:
            print("\nYou have successfully logged into the system")
            return
        else:
            print("\nThis user name or password does not exist\n")
            ATTEMPTS -= 1
    print("you have been locked out.")

main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM