while True or while 1

MRAB python at mrabarnett.plus.com
Sun Jan 22 11:13:37 EST 2012

On 22/01/2012 16:05, Dan Sommers wrote:
> On Sun, 22 Jan 2012 05:25:25 +0000, Steven D'Aprano wrote:
>>  Or they've been writing Python code since before version 2.2 when True
>>  and False were introduced, and so they are used to the "while 1" idiom
>>  and never lost the habit.
> That would be me.
> As per a now-ancient suggestion on this mailing list (I believe it was by
> Tim Peters), I've also been known to use a non-empty, literal Python
> string as a self-documenting, forever-True value in the typical loop-and-a-
> half cnstruct:
>      while "the temperature is too big":
>          temperature = get_temperature()
>          if temperature<= threshold:
>              break
>          process_temperature(temperature)
> This way, even though the loop condition is buried inside the loop (which
> could be longer than four lines), it is apparent as soon as I encounter
> the loop.
And the output of "dis" shows that it's optimised to a forever loop.

> With the advent of the "with" statement, though, these loops are slowly
> disappearing.

More information about the Python-list mailing list