empty clause of for loops

Steven D'Aprano steve at pearwood.info
Wed Mar 16 20:27:44 EDT 2016


On Thu, 17 Mar 2016 05:05 am, Sven R. Kunze wrote:

> What I don't understand is why Python features "if break, then no else
> clause", but "if empty, then empty clause".
> 
> I found this excellent post:
> https://shahriar.svbtle.com/pythons-else-clause-in-loops

That post describes the motivating use-case for the introduction
of "if...else", and why break skips the "else" clause:


for x in data:
    if meets_condition(x):
        break
else:
    # raise error or do additional processing 


It might help to realise that the "else" clause is misnamed. It should be
called "then":

for x in data:
    block
then:
    block


The "then" (actually "else") block is executed *after* the for-loop, unless
you jump out of that chunk of code by raising an exception, calling return,
or break.

As a beginner, it took me years of misunderstanding before I finally
understood for...else and while...else, because I kept coming back to the
thought that the else block was executed if the for/while block *didn't*
execute. I couldn't get code with for...else to work right and I didn't
understand why until finally the penny dropped and realised that "else"
should be called "then".



-- 
Steven




More information about the Python-list mailing list