【发布时间】:2020-06-16 03:13:13
【问题描述】:
我一周前开始了我的编程之旅,之前的编码知识为零。 我还观看了有关如何发布堆栈溢出问题的视频,因此希望获得建设性反馈。
详情:
语言 - Python
版本 - 3.8.3
编辑器 - VS 代码
我正在尝试编写一个程序,该程序接受用户输入并检查它是否是有效密码。如果是,则显示“正确”并退出程序,如果不正确,则显示剩余尝试次数,总共3次,并再次要求输入。
我刚刚在我的教程中到达了 WHILE 循环部分,并用它来制作程序。
msg = input("What's the secret password: ")
# Password attempt is 3 times, starts at 2, then 1 and ends when counter is 0
num = 2
# bananas is the correct password
while msg != "bananas":
if num == 0:
print("Too many wrong attempts. You are locked out!") # exhausted all 3 attempts, should print given message.
else:
print(f"Wrong Password! You have {num} chances left") # password incorrect, display attempts left
msg = input("What's the secret password: ")
num = num - 1
print("Correct")
问题
如果我立即运行它并提供正确的密码,或者在尝试 1-2 次失败后,它会按预期运行。 但是如果我输入错误 3 次,它就会进入显示消息的循环
错误尝试太多。你被锁定了!
并且永远打印出来。我无法弄清楚在哪里退出循环,以便它只显示一次消息并退出程序。
请帮助解决问题。
【问题讨论】:
标签: python python-3.x loops while-loop