empty clause of for loops

Sven R. Kunze srkunze at mail.de
Thu Mar 17 08:01:59 EDT 2016


On 17.03.2016 01:27, Steven D'Aprano wrote:
> 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.

That's true. I needed to explain this to few people and I always need 
several attempts/starts to get it right in a simple statement:

'If you do a "break", then "else" is NOT executed.' I think the "NOT" 
results in heavy mental lifting.

> 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".

That's actually a fine idea. One could even say: "finally".

Best,
Sven



More information about the Python-list mailing list