Loop until condition is true

Shane Hathaway shane at hathawaymix.org
Wed Jun 22 00:14:07 EDT 2005


Remi Villatel wrote:
> Hi there,
> 
> There is always a "nice" way to do things in Python but this time I can't 
> find one.
> 
> What I'm trying to achieve is a conditionnal loop of which the condition 
> test would be done at the end so the loop is executed at least once. It's 
> some way the opposite of "while".
> 
> So far, all I got is:
> 
> while True:
> 	some(code)
> 	if final_condition is True:
> 		break
> 	#
> #
> 
> What I don't find so "nice" is to have to build an infinite loop only to 
> break it.

FWIW, my own experience is that the "while True" idiom is actually safer
and better than alternatives like do/while.  I used to write do/while
loops all the time, but I wound up with more than my fair share of
unintentionally infinite loops.  I put too much trust in the syntax: I
expected that since I was using the cleaner construct, I didn't have to
worry about infinite loops.

Now, I think of "while True" not as an infinite loop, but rather as a
sign reminding me to be wary of looping infinitely in a particular spot.
 I feel like this has resulted in a lot fewer infinite loops in my own
code.  Now I believe that any loop that can't be represented well with
"for" or a conditional "while" has enough inherent complexity to justify
a warning sign, and "while True" has bright yellow flashing lights all
over it.  Thus I'm quite in favor of the status quo.

Shane



More information about the Python-list mailing list