簡體   English   中英

為什么這個while循環進入無限狀態而不是在3次迭代后停止?

[英]Why is this while loop entering infinite state instead of stopping after 3 iterations?

我試圖找出猜測的詞是否正確。 3次錯誤嘗試后,它進入無限循環。 為什么while循環在第三次迭代后沒有結束?

secret_word = "python"
guess = ""
attempt = 1

while guess != secret_word:
    if attempt < 3:
        guess = input("your word: ")
        attempt += 1

    else:
        print("time up!")

print("win!")

一旦attemp >= 3 ,您的 while 循環就開始執行else子句。 問題是循環沒有完成,因為用戶沒有猜到,guess 不等於 secret_word。

修復它的一種方法是在print('time up!')之后添加一個break語句。 但是,這也會打印'win' 為了防止最后一點,將print('win')包裝在else語句中:

print('win')

進入:

else:
    print('win')

如果循環正常退出(條件為假),而不是通過break語句或異常退出,則執行 while 循環中的 else 條件。

secret_word = 'python'
attempts = 3

for attempt in range(attempts):
    guess = input(f'Attempt {attempt+1}: ')
    if guess == secret_word:
        print('You won!')
        break
    else:
        print('try again...')

暫無
暫無

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

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