程序不断重复。 (Python)

Program keeps repeating itself. (Python)

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 编写一个简单的密码脚本,但程序并没有停止循环输入 "enter the password" 即使在我输入正确之后,当我输入正确时错了五次它仍然循环。有人知道我该如何解决这个问题吗?

谢谢。

您的代码有 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() 值将存储为字符串,因此您正在比较始终 return False 的不同类型。您需要将 passwordEntry 转换为 int,或者与 '1234' 字符串进行比较。

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

问题是你实际上并没有递减 attemptsRemaining
你需要做相当于 attemptsRemaining = attemptsRemaining - 1.

更常见和更简洁,你可以做到attemptsRemaining -= 1

您会发现的另一个问题(不太明显)是当您调用 input 时,该值将存储为字符串。您正在与 1234 整数进行比较,因此它将始终 return False 并且永远不会认为您的密码正确,即使它是 1234.

最后,您需要确保在密码正确时 break 退出 while 循环。否则,您将陷入循环!

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