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?
The continue keyword is used to end the current iteration in a for loop (or a while loop), and continues to the next iteration.
Continue statement in java can be used with for , while and do-while loop.
The continue statement can be used with any other loop also like while or do while in a similar way as it is used with for loop above. Exercise Problem: Given a number n, print triangular pattern. We are allowed to use only one loop.
Python continue statementThe continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With