Loop with else clause

Ben Finney ben+python at benfinney.id.au
Tue Feb 5 03:12:03 EST 2019


DL Neil <PythonList at DancesWithMice.info> writes:

> Possible solution:
> To make anything more than the trivial case readable, I think I'd put
> the list processing into one function, and the exception into another
> (except that this case is so trivial), ie
>
> 	if list:
> 		process_list() #the heading and for-loop, as above
> 	else:
> 		print( "Sorry...

(As an aside: It's best to avoid choosing names like ‘list’ that clobber
built-in names; your code examples are harder to read that way. I'll
assume a different name, ‘ipsums’.)

One aspect of that example I would prefer to avoid: It scatters the
handling of the list to different locations in the code. It's not
obvious from the purpose of ‘process_list’ whether that function should
be handling an empty list; this could lead to double-handling in
different locations.

An alternative to consider::

    if ipsums:
        for item in ipsums:
            process_item(item)
    else:
        print("Sorry...")

An advantage of this is that the handling of the list is all in the same
place, where changing that logic later will be easier. The
‘process_item’ then just assumes some other code has decided which items
to handle; it becomes correspondingly simpler.

-- 
 \       “Two possibilities exist: Either we are alone in the Universe |
  `\   or we are not. Both are equally terrifying.” —Arthur C. Clarke, |
_o__)                                                             1999 |
Ben Finney



More information about the Python-list mailing list