Reputation: 42439
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?
Upvotes: 7
Views: 9058
Reputation: 310097
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.
1This is complete guess, I don't have any real data to support this claim :)
Upvotes: 13
Reputation: 15017
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
Upvotes: 2
Reputation: 3228
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.
Upvotes: 2