Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a for-loop where the variable's value is equal to the stop value of range when the loop runs to the end in Python?

Tags:

python

I'm having a conceptual problem porting this from C to Python:

int p;
for (p = 32; p < 64; p += 2) {
    if (some condition)
        break;
    do some stuff
}
return p;

Converting the loop to for p in range(32,64,2) does not work. This is because after the loop ends, p is equal 62 instead of 64.

I can do it with a while loop easily:

p = 32
while p < 64:
    if (some condition):
        break
    do some stuff
    p += 2
return p

But I'm looking for a Pythonic way.

like image 296
goodvibration Avatar asked Jul 16 '17 13:07

goodvibration


People also ask

How do you repeat a loop for a certain number?

You can do the same type of for loop if you want to loop over every character in a string. To loop through a set of code a certain number of times, you can use the range() function, which returns a list of numbers starting from 0 to the specified end number.

How do you end a for loop if a condition is met?

Tips. The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop.

How do you limit a loop in Python?

zip(range(limit), items) Using Python 3, zip and range return iterables, which pipeline the data instead of materializing the data in lists for intermediate steps. To get the same behavior in Python 2, just substitute xrange for range and itertools. izip for zip .


2 Answers

you can use else for for loop in case condition isn't met to add 2 like C loop does:

for p in range(32, 64, 2):
   if some_condition:
       break
else:
    # only executed if for loop iterates to the end
    p += 2
like image 169
Jean-François Fabre Avatar answered Sep 28 '22 03:09

Jean-François Fabre


Extend the range, but include a second "redundant" break condition.

for p in range(32, 65, 2):
    if p >= 64 or (some condition):
        break
    # do stuff

(The only significant difference between this and Jean-François Fabre's answer is which piece of the logic you duplicate: testing if p is out of range, or incrementing p.)

like image 44
chepner Avatar answered Sep 28 '22 01:09

chepner