Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing step in Python loop [duplicate]

Tags:

python

In Python 2.7 I want to modify the step of a for loop in function of the specifics conditions satisfied in the loop. Something like this:

step = 1
for i in range(1, 100, step):
    if ...... :
        step = 1
        #do stuff
    else:
        step = 2
        #do other stuff

but it seems that this can't be done, step is always 1.

Thanks.

like image 498
David Avatar asked Sep 12 '17 15:09

David


2 Answers

you would need to increment step manually which can be done using a while loop. checkout difference between while and for loop.

The for statement iterates through a collection or iterable object or generator function.

The while statement simply loops until a condition is False.

if you use a while loop your code would look something like this:

step = 1
i = 1
while i < 100:
    if ...... :
        step = 1
        #do stuff
    else:
        step = 2
        #do other stuff
    i = i + step
like image 154
OLIVER.KOO Avatar answered Oct 28 '22 08:10

OLIVER.KOO


import numpy as np
for i in np.arange(start,stop,stepwidth):
    # your stuff
like image 41
bieboebap Avatar answered Oct 28 '22 08:10

bieboebap