[Tutor] Else vs. Continue

Dominik George nik at naturalnet.de
Sun Nov 24 22:41:13 CET 2013


Hi,

> 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. Is my
> assumption correct or wrong? If the latter is the case: Can you give
> me examples of continue usage that couldn't be done with else?

In general, you can translate quite many code samples into different
ones.

The difference is that else is used in an if control block, and continue
is used only in loops and does exactly one thing: Skip the rest of the
loop body, and begin the next iteration.

Of course, you could do a lot of tests in the loop and use a lot of
else: pass blocks that, after hitting a point where you want to escape
the loop, skip the rest of the effective code, but that's cumbersome.

If you want to exit a loop at a certain point, just use continue (or
break to skip all remaining operations).

To add to your confusion: while loops do have an else part in Python:

while CONDITION:
    ... do something ...
else:
    ... do something else ...

The else part is executed exactly in the case that CONDITION is no
longer True - but *not* when you break from the loop before that.

-nik

-- 
* concerning Mozilla code leaking assertion failures to tty without D-BUS *
<mirabilos> That means, D-BUS is a tool that makes software look better
            than it actually is.

PGP-Fingerprint: 3C9D 54A4 7575 C026 FB17  FD26 B79A 3C16 A0C4 F296
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 905 bytes
Desc: Digital signature
URL: <http://mail.python.org/pipermail/tutor/attachments/20131124/61273d06/attachment.sig>


More information about the Tutor mailing list