Extension of while syntax

Ben Finney ben+python at benfinney.id.au
Thu Dec 11 21:37:33 EST 2014


Nelson Crosby <nc at sourcecomb.com> writes:

> I was thinking a bit about the following pattern:
>
> value = get_some_value()
> while value in undesired_values:
>     value = get_some_value()

I think that's an anti-pattern (because of the repetition, as you say).

An improvement::

    value = some_default_value_such_as_None
    while value in undesired_values:
        value = get_some_value()

More common and generally useful::

    while True:
        value = get_some_value()
        if value not in undesired_values:
            break

> What are other's thoughts on this?

I think there are already clean ways to deal with this in common use.

<URL:https://wiki.python.org/moin/WhileLoop>
<URL:https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops>

-- 
 \       “… one of the main causes of the fall of the Roman Empire was |
  `\        that, lacking zero, they had no way to indicate successful |
_o__)                  termination of their C programs.” —Robert Firth |
Ben Finney




More information about the Python-list mailing list