【问题标题】:Program keeps repeating itself. (Python)程序不断重复。 (Python)
【发布时间】:2020-06-11 13:44:58
【问题描述】:
attemptsRemaining = 5
if attemptsRemaining == 0:
print("Entry failed. Locking program.")
exit()
while attemptsRemaining > 0:
passwordEntry = input("Enter the password to access the data: ")
if passwordEntry == 1234:
print("test")
else:
attemptsRemaining -1
所以,我正在使用 Python 编写一个简单的密码脚本,但是即使我正确输入了“输入密码”输入,程序也不会停止循环,当我输入错误五次时它仍然循环.有谁知道我该如何解决这个问题?
谢谢。
【问题讨论】:
标签:
python
loops
while-loop
passwords
【解决方案1】:
您的代码有 3 个问题。
首先,你要在输入正确密码后打破while循环。
其次,您的 else 子句中有错字:
应该是-= 1
attemptsRemaining - 1 计算出正确的值,但不将其分配回变量。
下面的代码应该适合你
attemptsRemaining = 5
if attemptsRemaining == 0:
print("Entry failed. Locking program.")
exit()
while attemptsRemaining > 0:
passwordEntry = input("Enter the password to access the data: ")
if passwordEntry == 1234: # if you get the password correct
print("test") # print test
break # and come out of the loop
else:
attemptsRemaining -=1
第三,您将用户输入的值与整数进行比较。 input() 值将存储为字符串,因此您正在比较始终返回 False 的不同类型。您需要将passwordEntry 转换为int,或与'1234' 比较字符串。
【解决方案2】:
问题是您实际上并没有递减attemptsRemaining。
你需要做相当于attemptsRemaining = attemptsRemaining - 1。
更常用和更简洁,您可以使用attemptsRemaining -= 1。
您会发现(不太明显)的另一个问题是,当您调用input 时,该值将存储为字符串。您正在与 1234 进行比较整数,因此它将始终返回 False 并且永远不会认为您的密码正确,即使它是 1234。
最后,当密码正确时,您需要确保 break 退出 while 循环。否则,您将陷入困境!
【解决方案3】:
attemptsRemaining = 5
while attemptsRemaining > 0:
passwordEntry = input("Enter the password to access the data: ")
if passwordEntry == 1234:
print("test")
break # exit loop
else:
attemptsRemaining -=1
if attemptsRemaining == 0:
print("Entry failed. Locking program.")
exit()
【解决方案4】:
执行 if 语句的正确方法。并在 5 次错误尝试后退出
attemptsRemaining = 5
while attemptsRemaining > 0:
passwordEntry = input("Enter the password to access the data: ")
if passwordEntry == "1":
print("test")
print (attemptsRemaining)
break
else:
attemptsRemaining = attemptsRemaining - 1
if attemptsRemaining == 0:
print("Entry failed. Locking program.")
exit()