本文介绍了更改for循环中的迭代次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 loopcount = 3 我在范围内(1,loopcount) somestring ='7' newcount = int(somestring) loopcount = newcount 所以我想要的是修改'内部'循环的范围。 我写了这个代码,期待for循环的范围会改变到(1,7)在第一个循环,但它没有发生。 相反,不管我输入什么号码,它只运行2次。 (我想6次..在这种情况下) 我检查使用打印这样的值: print loopcount somestring ='7' newcount = int(somestring)$ p $ loopcount = 3 loopcount = newcount print loopcount #output: 3 7 7 7 有什么不对?这个数字已经被改变了。 我的思路在哪里错了? 解决方案范围是根据 loopcount 在被调用的时候创建的 - 任何发生在后面的loopcount都是不相关的。你可能想要的是一个while语句: loopcount = 3 i = 1 while I< loopcount: somestring ='7' loopcount = int(somestring)i + = 1 在 i 为true,如果为true,则运行它所包含的语句。在这种情况下,每次通过循环时,i都增加1.由于第一次循环计数设置为7,循环将运行六次,对于i = 1,2,3,4,5和6 。 一旦条件为假,当 i = 7 时,while循环停止运行。 (我不知道你的实际用例是什么,但你可能不需要分配newcount,所以我删除了它)。 I have code like this:loopcount = 3for i in range(1, loopcount) somestring = '7' newcount = int(somestring) loopcount = newcountso 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:3777What is wrong? the number has been changed.Where is my thinking wrong? 解决方案 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 = 3i = 1while i < loopcount: somestring = '7' loopcount = int(somestring) i += 1The 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). 这篇关于更改for循环中的迭代次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-18 17:18