Stackoverflow question about this resulted in a detailed discussion on this topic. To summarize:
for
or a while
loopIn Python: If you need to modify the counter from within the loop before incrementing to the next number in the series that controls the loop, you should use a while
loop. If the loop will increment a set number of times and you do not need to modify the counter (you will just repeat some action or actions x times), then a for
loop is a good choice.
Code samples that follow illustrate the compexities of trying to defy this simple guideline.
In [2]:
def jumpable_range(start, stop):
i = start
while i <= stop:
j = yield i
i = i + 1 if j is None else j
In [3]:
R = jumpable_range(2, 10)
for i in R:
if i==5:
i = R.send(8)
print(i)
In [11]:
## so how to integrate into original code:
endRw=5
lenDF=97 # 1160
Q = jumpable_range(0,lenDF)
for i in Q:
print("i: ", i)
endIndx = i + endRw
if endIndx > lenDF:
endIndx = lenDF
if i == endIndx: break
print("Range to use: ", i, ":", endIndx)
# this line is a mockup for an index that is built and used
# in the real code to do something to a pandas DF
i = Q.send(endIndx-1)
print("i at end of loop", i)
In [10]:
endRw=5
lenDF=97 # 1160
i = 0
while i < lenDF:
print("i: ", i)
endIndx = i + endRw
if endIndx > lenDF:
endIndx = lenDF
print("Range to use: ", i, ":", endIndx)
# this line is a mockup for an index that is built and used
# in the real code to do something to a pandas DF
i = endIndx
print("i at end of loop: ", i)
In [9]:
endRw=5
lenDF=97 # 1160
for i in range(0, lenDF, endRw):
my_range = min(endRw, lenDF-i)
print("Range to use: ", i, ":", i+my_range)
In [1]:
endRw=5
lenDF=97 # 1160
for i in range(0, lenDF, endRw):
endIndx = min(i+endRw, lenDF)
print("Range to use: ", i, ":", endIndx)
In [ ]: