Changing the number of iterations in a for loop

前端 未结 8 1376
死守一世寂寞
死守一世寂寞 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 11:56

    When the range() function is evaluated in the for-loop it generates a sequence of values (ie a list) that will be used to iterate over.

    range() uses the value of loopcount for this. However, once that sequence has been generated, nothing you do inside the loop will change that list, i.e., even if you change loopcount later, the original list will stay the same => the number of iterations will stay the same.

    In your case:

    loopcount = 3
    for i in range(1, loopcount):
    

    becomes

    for i in [1, 2]:
    

    So your loop iterates twice, since you have 2 print statements in the loop your get 4 lines of output. Note that you are printing the value of loopcount which is initially 3, but then gets set (and reset) to 7.

    If you want to be able to change the iteration number dynamically consider using a while-loop instead. Of course you can always stop/exit any loop early with the use of the break statement.

    Also,

       somestring = '7'
       newcount = int(somestring)
    

    can be simplified to just

       newcount = 7
    

提交回复
热议问题