for / while else doesn't make sense

Steven D'Aprano steve at pearwood.info
Fri Jun 3 22:20:47 EDT 2016


On Sat, 4 Jun 2016 02:22 am, Lawrence D’Oliveiro wrote:

> In Python you write a loop with one exit in one way, a loop with two exits
> in a different way, and a loop with more than two exits in yet another
> entirely different way. Can you say “cognitive burden”?

Yes I can, but I don't see the point.

In Python, you write a loop with one exit one way:

for x in seq:
    do_something()


and a loop with two or more exits a *trivially different* way:

for x in seq:
    do_something()
    if condition:
        break
    if another_condition:
        break


You can put as many or as few break statements in the loop as you like,
whether it is zero or one or ten or a thousand, the for-loop is written the
same way, with a slight difference only when going from the "no early exit"
case to "at least one early exit" case. How is this a cognitive burden?

Programming is about composing code from smaller components in this way.
Here is how you add two numbers:

    result = a + b

and three numbers:

    result = a + b + c

and four numbers:

    result = a + b + c + d

This isn't three or more different ways to add numbers, depending on how
many numbers you have to add. It is ONE way to add, composed as many times
as you need it. For-loops are no different: you can exit the loop by
reaching the end and exiting, or you can exit early by using break. The
number of breaks is just composition.




-- 
Steven



More information about the Python-list mailing list