Loop until condition is true

Donn Cave donn at drizzle.com
Sat Jun 18 08:03:38 CEST 2005


Quoth Remi Villatel <maxilys at SPAMCOP_tele2.fr>:

| 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.
|
| Is there a better recipe?

It depends, but that isn't too bad.  The alternative would be flag
variable, like "looping = 1; while looping: ..."

The construct you're looking for is "until" in C, and there have been
plenty of proposals to add this or other improvements to Python's
repertoire.  As far as I know, it hasn't happened because it isn't
really needed.  If you look at C code, at least in my experience the
"until" loop is quite rarely used.  (I don't see it once in the source
to Python 2.4, for example.)  Meanwhile, the "while True" (or "while 1")
idiom is very familiar to Python programmers (just as the Python source
has dozens of "for (;;)"), so it's preferred for legibility.  It's nice,
don't worry.

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list