[Tutor] Else vs. Continue
Mark Lawrence
breamoreboy at yahoo.co.uk
Mon Nov 25 00:28:06 CET 2013
On 24/11/2013 21:41, Dominik George wrote:
> 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
>
To add to your confusion: for loops can also have an else part in
Python:
http://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
--
Python is the second best programming language in the world.
But the best has yet to be invented. Christian Tismer
Mark Lawrence
More information about the Tutor
mailing list