for -- else: what was the motivation?

Chris Angelico rosuav at gmail.com
Mon Oct 10 18:00:11 EDT 2022


On Tue, 11 Oct 2022 at 08:55, Robert Latest via Python-list
<python-list at python.org> wrote:
>
> Chris Angelico wrote:
> > Yes, I'm aware that code readability becomes irrelevant for
> > short-duration projects. Beside the point. I'm wondering how important
> > it really is to have the shortest block first.
>
> I usually put the most expected / frequent / not negated block first if the
> whole if/else statement is not "too long". Sometimes whatever you want to do
> becomes pointless if a certain conditions is not met, in which case I do an
> early break or return and have no else block at all.
>
> > Given that for-else is an excellent, if rarely-used, construct
>
> I knew it existed but coming from C I never thought to exploit it. I know I
> wrote loops like this:
>
>     found = None
>     while not found:
>         found = search(something)
>         if found:
>             break
>     if not found:
>         complain()
>
> Need to look into using "else" in these cases.

Yep, that's exactly what for-else is great at!

while True:
    if search(something): break
else:
    complain()

(although rather than a "while True", you're probably iterating over
things to search for, in some way)

ChrisA


More information about the Python-list mailing list