繁体   English   中英

为什么我会不断尝试输入6次而不是3次?

[英]Why do I keep getting 6 input attempts instead of 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次提示用户。

由于您在while的测试是pw_count <= pw_attempt ,因此当pw_count为3时它将继续进行,请再询问3次,从而使您达到6。

您一次要输入3次密码。 您已经知道可以使用pw_count < pw_attempt解决此pw_count < pw_attempt 6次的原因是因为经过1次迭代(要求3次,其中pw_count = 0)。 条件pw_count <= pw_attempt现在仍然适用,因为pw_count = pw_attempt现在将继续要求输入密码3次,共6

确实只需遵循代码,您将得出答案。 当我遵循您的代码并将其从Python转换为英语时,我得到以下信息:

  • 要求输入密码并存储在密码中
  • 要求重新输入(首次尝试)并存储在pwre中
  • pwre与pw有区别吗? (假设是),并且计数(0)小于或等于pw_attempt(3)吗? (是的,较小的)
  • 向用户询问3次以上,并在用户每次失败时递增计数(此后最终计数为3)
  • 回到循环头
  • pwre与pw有区别吗? (假设是),并且count(3)小于或等于pw_attempt(3)吗? (是的,等于!)
  • 向用户询问3次以上,并在每次用户失败时递增计数(此后最终计数为6。
  • 回到循环头
  • pwre与pw有区别吗? (假设是),并且count(6)小于或等于pw_attempt(3)吗? (不,更大,所以循环终止)

您可以这样简化:

pw_count = 0
pw_attempt = 3
pw = input("Please enter your password: ")
while pw_count < pw_attempt:
    pw_count += 1
    if pw_count == 1:
        pwre = input("Please re-enter your password: ")
    else:
        pwre = input("Your password doesn't match, please try again: ")
    if pw == pwre:
        print("Password is confirmed")
        break

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM