I have code like this:
loopcount = 3
for i in range(1, loopcount)
somestring = '7'
newcount = int(somestring)
loopcount = newcount
so what I want is to modify the range of the for ‘inside’ the loop.
I wrote this code expecting the range of the for loop would change to (1,7) during the first loop, but it didn’t happen.
Instead, no matter what number I put in, it only runs 2 times. (I want 6 times.. in this case)
I checked the value using print like this:
loopcount = 3
for i in range(1, loopcount)
print loopcount
somestring = '7'
newcount = int(somestring)
loopcount = newcount
print loopcount
#output:
3
7
7
7
What is wrong? the number has been changed.
Where is my thinking wrong?
The range is created based on the value of
loopcountat the time it is called–anything that happens to loopcount afterwards is irrelevant. What you probably want is a while statement:The
whiletests that the conditioni < loopcountis true, and if true, if runs the statements that it contains. In this case, on each pass through the loop, i is increased by 1. Since loopcount is set to 7 on the first time through, the loop will run six times, for i = 1,2,3,4,5 and 6.Once the condition is false, when
i = 7, the while loop ceases to run.(I don’t know what your actual use case is, but you may not need to assign newcount, so I removed that).