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