首页 > 解决方案 > 内部 While 循环只运行一次 - Python

问题描述

我正在为程序使用嵌套的 While 循环,我注意到内部的 while 循环只运行一次。

i = 0
j = 0
while i < 5:
    while j < 5:
        print('Inner While Loop')
        j += 1
    print('Outer While Loop')
    i = i+1

输出 :

Inner While Loop
Inner While Loop
Inner While Loop
Inner While Loop
Inner While Loop
Outer While Loop
Outer While Loop
Outer While Loop
Outer While Loop
Outer While Loop

我想要的是当外部循环再次启动时内部循环也再次运行。

标签: python

解决方案


我认为您的问题是您没有重置 j 变量。所以下一次外循环执行时,j 仍然是 5,你跳过内循环。例如,如果您更改代码以在第一个 while 循环中初始化 j ,我相信一切都应该正常工作:

i = 0
while i < 5:
    j = 0 # Moved to inside the while loop
    while j < 5:
        print('Inner While Loop')
        j += 1
    print('Outer While Loop')
    i = i+1

推荐阅读