[Tutor] Continue Statement
Peter Otten
__peter__ at web.de
Mon Dec 16 18:29:58 CET 2013
Alina Campana wrote:
> Hello dear tutorlist,
Welcome!
> I feel terribly ashamed for my bad english...
> Yet I'll try to form my question:
> It is about the continue statement in python.I wrote this code
> i = 0while (i < 10): if i == 5: continue print i i+=1
> What i expected was an output like12346789
> Instead it seems to freeze after 4. The shell input symbol is blinking.
>
> I bet this is easy enough for pros but I really got my problem with
> understanding the reason why. Okay thank you people, I go now learn better
> english ^^
As long as we can understand you at all a few quirks in your English don't
matter. Quite a few of as aren't native speakers either.
What does matter is how you format your post -- use text-only if possible at
all. Anyway, I'm guessing that your code originally looked like this:
i = 0
while (i < 10):
if i == 5:
continue
print i
i+=1
Look at the while loop closely -- for 0, 1, 2, 3, and 4 it does not enter
the if suite. But with i == 5 it executes the continue statement, i. e. it
goes right back to the while-test. Both `print i` and `i += 1` are skipped,
i stays at the value 5 forever.
What you want is to skip the print, but not the increment, and there is no
straight-forward way to do that using continue and a while loop. But how
about using for?
for i in range(10):
if i == 5:
continue
print i
In fact I would write it without continue:
for i in range(10):
if i != 5:
print i
Now a variant with while (not recommended), just to show how you could skip
part of the code using continue:
i = 0
while i < 10:
k = i
i += 1
if k == 5:
continue
print k
But even that would look better without continue:
i = 0
while i < 10:
if i != 5:
print i
i += 1
More information about the Tutor
mailing list