osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

The "loop and a half"


Steve D'Aprano <steve+python at pearwood.info> writes:

> On Wed, 4 Oct 2017 04:45 am, Rhodri James wrote:
>
>> On 03/10/17 18:29, Stefan Ram wrote:
>>>    Is this the best way to write a "loop and a half" in Python?
>> 
>> Define "best".
>
> I'd start with "define loop and a half".

What it means to me is this pattern:

  while True:
      ... statements that don't exit the loop ...
      if condition: break
      ... more statements that don't exit the loop ...

When the first set of statements is null, it's just a while loop.  When
the second is null, it's just a do ... while (in languages that have
it).

Where both sets are present some languages encourage putting the first
set into the condition of the loop.  For example, in Algol 68 an
expression can be replaced by a statement sequence that ends in an
expression.  C encourages the same, provided the first set of statements
is very simple.  The classic example being

  while ((some_var = some_input_function()) != some_error_value) {
     ... process some_var ...
  }

In Pascal, you sometimes had to duplicate the first set of statements:

  ... statements that don't exit the loop ...
  while condition
  begin
      ... more statements that don't exit the loop ...
      ... statements that don't exit the loop ...
  end

-- 
Ben.