[Tutor] Else vs. Continue
Steven D'Aprano
steve at pearwood.info
Mon Nov 25 02:40:16 CET 2013
On Sun, Nov 24, 2013 at 10:32:20PM +0100, Rafael Knuth wrote:
> Hej there,
>
> I stumbled upon the "continue" statement and to me it looks like it
> does exactly the same as else. I tested both else and continue in a
> little program and I don't see any differences between both.
"continue" and "else" are completely unrelated.
"continue" can only be inside a for-loop or a while-loop, and it
immediately jumps back to the beginning of the next loop. If I write
this:
for i in range(10):
print(i)
continue
print("This will never be printed")
it will print the numbers 0 through 9 but never reach the second print.
Obviously, unconditionally using "continue" in this way is silly. If you
don't ever want the second print line, why not just leave it out? But it
is useful to conditionally continue or not, which means you will nearly
always see "continue" somewhere inside an if...elif...else block.
For example:
for i in range(20):
if i%2 == 0:
print("Skipping an even number")
continue
print("Odd number {}".format(i))
print("Remainder when divided by three is: {}".format(i%3))
The continue need not be inside the "if" block. It could be inside an
"elif" or "else" block instead.
--
Steven
More information about the Tutor
mailing list