首页 > 解决方案 > 为什么我不断收到 6 次输入尝试而不是 3 次?

问题描述

我一直在尝试一些东西,并遇到了这个问题。用户必须输入密码并尝试 3 次,否则将被拒之门外。但我不断尝试 6 次。我知道我可以解决这个问题,但使用 pw_count < pw_attempt 而不是 pw_count <= pw_attempt。当我使用 <= 时,我只想了解它背后的逻辑

a1 = ""
a2 = ""
a3 = ""
pw_count = 0
pw_attempt = 3
pw = input("Please enter your password: ")
pwre = input("Please re-enter your password: ")

while pw != pwre and pw_count <= pw_attempt:
    a1 = input("Your password doesn't match, please try again: ")
    pw_count += 1
    if a1 == pw:
        break
    else:
        a2 = input("Your password doesn't match, please try again: ")
    pw_count += 1
    if a2 == pw:
        break
    else:
        a3 = input("Your password doesn't match, please try again: ")
    pw_count += 1
    if a3 == pw:
        break

    if (pw == pwre and pw_count <= pw_attempt) or (a1 == pw and pw_count <= pw_attempt) or (a2 == pw and pw_count <= pw_attempt) or (a3 == pw and pw_count <= pw_attempt):
        print("Password is confirmed")
    else:
        print("You have entered the wrong password too many times")

我只是希望程序提示用户 3 次尝试而不是 6 次。

标签: python

解决方案


由于您在whileis的测试pw_count <= pw_attempt,它将在 3时继续pw_count,再询问 3 次,您将获得 6。


推荐阅读