Consider the following code in C:
for(int i=0; i<10 && some_condition; ++i){
do_something();
}
I would like to write something similar in Python. The best version I can think of is:
i = 0
while some_condition and i<10:
do_something()
i+=1
Frankly, I don’t like while loops that imitate for loops. This is due to the risk of forgetting to increment the counter variable. Another option, that addressess this risk is:
for i in range(10):
if not some_condition: break
do_something()
Important clarifications
-
some_conditionis not meant to be calculated during the loop, but rather to specify whether to start the loop in the first place -
I’m referring to Python2.6
Which style is preferred? Is there a better idiom to do this?
In general, the “
range+break” style is preferred – but in Python 2.x, usexrangeinstead ofrangefor iteration (this creates the values on-demand instead of actually making a list of numbers).But it always depends. What’s special about the number 10 in this context? What exactly is
some_condition? Etc.Response to update:
It sounds as though
some_conditionis a “loop invariant”, i.e. will not change during the loop. In that case, we should just test it first: