简体   繁体   中英

Is the continue statement necessary in a while loop?

I'm confused about the use of the continue statement in a while loop.

In this highly upvoted answer , continue is used inside a while loop to indicate that the execution should continue (obviously). It's definition also mentions its use in a while loop:

continue may only occur syntactically nested in a for or while loop

But in this (also highly upvoted) question about the use of continue , all examples are given using a for loop.

It would also appear, given the tests I've run, that it is completely unnecessary. This code:

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

works just as good as this one:

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

What am I missing?

Here's a really simple example where continue actually does something measureable:

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

You'll notice that if you run this, you won't see dog printed. That's because when python sees continue , it skips the rest of the while suite and starts over from the top.

You won't see 'horse' or 'cow' either because when 'horse' is seen, we encounter the break which exits the while suite entirely.

With all that said, I'll just say that over 90% 1 of loops won't need a continue statement.

1 This is complete guess, I don't have any real data to support this claim :)

continue just means skip to the next iteration of the loop. The behavior here is the same because nothing further happens after the continue statement anyways.

The docs you quoted are just saying that you can only use continue inside of a loop structure - outside, it's meaningless.

continue is only necessary if you want to jump to the next iteration of a loop without doing the rest of the loop. It has no effect if it's the last statement to be run.

break exits the loop altogether.

An example:

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')

result:

before loop
3
4
after loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM