簡體   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