首页 > 解决方案 > Python - WHILE 循环嵌套在 FOR 循环中

问题描述

我试图实现这个输出:

0;12
1;24
2;36
3;48
4;60

...但我得到了这个:

0;12
1;12
2;12
3;12
4;12

这是代码:

iter = 0
count = 0
letter = 0
for iter in range(5):
    while letter < len("hello, world"):
        letter+=1
        count+=1
    print("Iteration " + str(iter) + "; count is: " + str(count))

我设法通过添加count*(iter+1)而不是count在打印语句中解决了这个问题,但我试图理解的是为什么每次新迭代开始时计数变量都会重置。提前致谢。

标签: pythonloopsfor-loopwhile-loopnested-loops

解决方案


letter始终为 13,因为它没有重新初始化。所以while循环只会执行一次。为了解决这个问题,

count = 0
for iter in range(5):
    letter = 0
    while letter < len("hello, world"):
        letter+=1
        count+=1
    print("Iteration " + str(iter) + "; count is: " + str(count))

推荐阅读