簡體   English   中英

5 次嘗試后如何退出 while-true 循環?

[英]How do I exit a while-true loop after 5 tries?

在我對計算機科學課程的介紹中,我們遇到了一個問題,我們必須創建一個循環來要求輸入人員密碼:

while True:
    password = input('What is your password?')
    if password == "abc123":
        break
    print("Please Try Again")
print("Welcome!")

我如何更改它,以便在 5 次嘗試/猜測密碼后,它顯示“密碼猜測全部結束”(或類似的東西)?

很多人不熟悉for...else結構,在這種情況下這是經典的

for attempt in range(5):
    password = input('What is your password?')
    if password == "abc123":
        print("Welcome!")
        break
else:
    print("all out of password guesses")

只有在沒有遇到break才會執行else

我同意@mauve 的觀點,即while循環並不是您要查找的內容,但您仍然可以使用計數器來實現:


max_tries = 5

while max_tries > 0: # We will decrement max_tries on each loop
    password = input('What is your password?')
    if password == "abc123":
        break
    print("Please Try Again")
    max_tries -= 1 # Decrement max_tries

if max_tries==0: # We tried too many times
    raise ValueError("Too many attempts!")

但是,使用 for 循環可能會更清楚一些


for i in range(max_tries):
    password = input('What is your password?')
    if password == "abc123":
        break
    print("Please Try Again")

if i == max_tries:
    raise ValueError("Too many attempts")

您可以在 for 循環的末尾使用else ,如下所示:

for i in range(max_tries):
    password = input('What is your password?')
    if password == "abc123":
        break
    print("Please Try Again")

else:
    raise ValueError("Too many attempts")

else將捕獲在循環結束之前沒有調用break的情況

實際上,如果您有循環限制,它就不是真正的“while true”。 您可以通過簡單地檢查密碼 5 次(或 n 次)來實現相同的目的。

try_num = 0
    while try_num <= 5:
        try_num = try_num + 1
        <rest of the code>

如果對於評估者/教師/作業所期望的特定格式,您必須有一個 while True ,您仍然可以使用此計數器並在while True內中斷。

try_num = 0
success = False
    while True:
        try_num = try_num + 1
        password = input('What is your password?')
        if password == "abc123":
            success = True
            break
        if try_num > 5:
            break
        print("Please Try Again")
if success == True:
    print("Welcome!")

您可能會看到選項 1 更優雅且更易於維護。

或者,您可以使用while ... else循環:

attempts = 0
while attempts < 5:
    password = input('What is your password?')
    if password == "abc123":
        print("Welcome!")
        break
    print("Please Try Again")
    attempts += 1
else:
    print('You have exceeded the number of allowed login attempts!')

做一個計數器,讓它倒計時。 while循環的條件應該是“當計數器達到 0 時”:

counter = 5
while counter > 0:
    counter -= 1
    password = input('What is your password?')
    if password == "abc123":
        break
    print("Please Try Again")
print("Welcome!")

與正確獲取密碼相比,您可能需要重寫一些內容,以便在計數器超時時發生不同的事情。


或者,更正確的版本是使用for循環而不是while循環:

for i in range(5):  # will execute 5 times with i = 0, 1, 2, 3, 4 in that order
    ...

但是如果您沒有將i變量用於任何特別的事情,那么一段while也可以正常工作。

我真的不僅在 python 中而且在編程方面都是菜鳥。 只是在隔離期間學習。 我想出了這個代碼來完成操作的要求。 我正在做一個在線課程和活動要求它。 這對您來說可能看起來很愚蠢,並且肯定有更好的方法來做我在這里所做的事情,但這是有效的。 (該活動要求使用 While True 進行)

rainbow = ("red, orange, yellow, green, blue, indigo, violet")
while True:
    color_input = input("Enter a color of the rainbow: ")
    if color_input.lower() in rainbow:
        print ("Great, you did it!! ")
        break
    else:
        print ("Wrong, you still have 3 tries.")

        while True:
            color_input = input("Enter a color of the rainbow: ")
            if color_input.lower() in rainbow:
                print ("Great, you did it")
                break
            else:
                print ("Wrong, you stil have 2 tries")

                while True:
                    color_input = input ("Enter a color of the rainbow: ")
                    if color_input.lower() in rainbow:
                        print ("Great, you did it")
                        break
                    else:
                        print ("Wrong, last try")

                        while True:
                            color_input = input("Enter a color of the rainbow: ")
                            if color_input.lower() in rainbow:
                                print ("Great, you finally did it")
                                break
                            else:
                                print ("You ran out attemps. Sorry, you failed")
                                break
                        break
                break
        break

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM