Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop with conditions in python

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

  1. some_condition is not meant to be calculated during the loop, but rather to specify whether to start the loop in the first place

  2. I'm referring to Python2.6

Which style is preferred? Is there a better idiom to do this?

like image 968
Boris Gorelik Avatar asked Dec 01 '10 11:12

Boris Gorelik


People also ask

How do you write a for loop in Python with condition?

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.

Can we use conditions in a loop?

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.

How do you combine for loop and if condition in Python?

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) .........]

Can you have 2 conditions in a while loop?

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.


1 Answers

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.

like image 102
Martin Tóth Avatar answered Sep 29 '22 12:09

Martin Tóth