我正在编写一个程序,要求用户输入密码。如果密码与我设置的常量匹配,则会打印出"成功登录的消息"。但是,如果密码不正确,则会提供剩余的猜测次数,并要求用户重试。该程序应在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()
答案 0 :(得分:3)
现在你永远不会退出你的while循环。要突破它,请使用break
关键字。
要完全退出程序,您需要import sys
和sys.exit()
我建议将这些添加到您的if ALLOWED == 0
声明中。
答案 1 :(得分:1)
您需要使用break
退出循环,或添加辅助条件,否则无论如何都会继续进行,直到密码正确为止。
所以,要么:
while (password != PASSWORD) and (ALLOWED > 0):
或者:
if ALLOWED == 0:
print("You have been locked out")
break
答案 2 :(得分:0)
条件密码!= PASSWORD不足以退出循环(仅当您输入正确的密码时才会退出循环)。同时添加条件while(密码!= PASSWORD和ALLOWED> 0)
答案 3 :(得分:0)
将print("You have been locked out")
更改为sys.exit("You have been locked out")
(或以其他方式退出main
)。请务必import sys
使用sys.exit
。
答案 4 :(得分:0)
您的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")
如果您的计划需要安全,您可能需要做更多研究。
答案 5 :(得分:0)
管理使它工作,但只是检查是否允许== 0,如果它确实打印“你被锁定”,如果允许< = 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()