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_condition
is 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?
For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages.
A conditional expression is a statement that evaluates to True or False . As long as the condition is true, the loop body (the indented block that follows) will execute any statements it contains. As soon as the condition evaluates to false, the loop terminates and no more statements will be executed.
If you want to combine a for loop with multiple conditions, then you have to use for loop with multiple if statements to check the conditions. If all the conditions are True, then the iterator is returned. Syntax: [iterator for iterator in iterable/range(sequence) if (condition1) if (condition2) .........]
Using multiple conditions As seen on line 4 the while loop has two conditions, one using the AND operator and the other using the OR operator. Note: The AND condition must be fulfilled for the loop to run. However, if either of the conditions on the OR side of the operator returns true , the loop will run.
This might not be related, but there's what I'm used to do... If some_condition
is simple enough, put it in a function and filter
items you iterate over:
def some_condition(element):
return True#False
for i in filter(some_condition, xrange(10)):
pass
You can use this approach also when you iterate over some list of elements.
selected = filter(some_condition, to_process)
for i, item in enumerate(selected):
pass
Again, this might not be your case, you should choose method of filtering items depending on your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With