[英]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轉換為英語時,我得到以下信息:
您可以這樣簡化:
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.