coding style - Loop with conditions in python -


consider following code in c:

for(int i=0; i<10 && some_condition; ++i){     do_something(); } 

i write similar in python. best version can think of is:

i = 0 while some_condition , i<10:     do_something()     i+=1 

frankly, don't while loops imitate for loops. due risk of forgetting increment counter variable. option, addressess risk is:

for in range(10):     if not some_condition: break     do_something() 

important clarifications

  1. some_condition not meant calculated during loop, rather specify whether start loop in first place

  2. i'm referring python2.6

which style preferred? there better idiom this?

in general, "range + break" style preferred - in python 2.x, use xrange instead of range iteration (this creates values on-demand instead of making list of numbers).

but depends. what's special number 10 in context? some_condition? etc.

response update:

it sounds though some_condition "loop invariant", i.e. not change during loop. in case, should test first:

if some_condition:   in xrange(10):     do_something() 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -