Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

python - Changing the number of iterations in a for loop

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...