Changing the number of iterations in a for loop

前端 未结 8 1372
死守一世寂寞
死守一世寂寞 2020-12-10 11:27

I have code like this:

loopcount = 3
for i in range(1, loopcount)
   somestring = \'7\'
   newcount = int(somestring)
   loopcount = newcount
8条回答
  •  鱼传尺愫
    2020-12-10 12:14

    The range is created based on the value of loopcount at the time it is called--anything that happens to loopcount afterwards is irrelevant. What you probably want is a while statement:

    loopcount = 3
    i = 1
    while i < loopcount:
        somestring = '7'
        loopcount = int(somestring)
        i += 1
    

    The while tests that the condition i < loopcount is 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).

提交回复
热议问题