簡體   English   中英

在 while 循環中是否需要 continue 語句?

[英]Is the continue statement necessary in a while loop?

我對在while循環中使用continue語句感到困惑。

在這個高度贊成的答案中,在while循環中使用continue來指示執行應該繼續(顯然)。 它的 定義還提到了它在while循環中的使用:

continue 只能在語法上嵌套在 for 或 while 循環中

但是在這個(也是高度贊成的)關於使用continue的問題中,所有示例都是使用for循環給出的。

考慮到我運行的測試,它也似乎完全沒有必要。 這段代碼:

while True:
    data = raw_input("Enter string in all caps: ")
    if not data.isupper():
        print("Try again.")
        continue
    else:
        break

和這個一樣好用:

while True:
    data = raw_input("Enter string in all caps: ")
    if not data.isupper():
        print("Try again.")
    else:
        break

我錯過了什么?

這是一個非常簡單的示例,其中continue實際上做了一些可測量的事情:

animals = ['dog', 'cat', 'pig', 'horse', 'cow']
while animals:
    a = animals.pop()
    if a == 'dog':
        continue
    elif a == 'horse':
        break
    print(a)

你會注意到,如果你運行它,你不會看到dog打印出來。 那是因為當 python 看到continue時,它​​會跳過其余的 while 套件並從頂部重新開始。

您也不會看到'horse''cow' ,因為當看到“ 'horse' ”時,我們會遇到完全退出while套件的中斷。

說了這么多,我只想說超過 90% 1的循環不需要continue語句。

1這是完全的猜測,我沒有任何真實數據來支持這個說法:)

continue只是意味着跳到循環的下一次迭代。 這里的行為是相同的,因為無論如何在continue語句之后都沒有發生任何進一步的事情。

您引用的文檔只是說您只能在循環結構內部使用continue - 在外部,它沒有意義。

僅當您想跳到循環的下一次迭代而不執行循環的其余部分時,才需要continue 如果它是要運行的最后一條語句,則它無效。

break完全退出循環。

一個例子:

items = [1, 2, 3, 4, 5]
print('before loop')
for item in items:
    if item == 5:
        break
    if item < 3:
        continue
    print(item)

print('after loop')

結果:

before loop
3
4
after loop

暫無
暫無

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

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