内部While循环仅运行一次-Python

时间:2020-05-02 17:36:51

标签: 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

我想要的是当外循环再次开始时,内循环也要再次运行。

3 个答案:

答案 0 :(得分:3)

我认为您的问题是您没有重置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

答案 1 :(得分:2)

在i循环中声明j=0

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

答案 2 :(得分:2)

为此,您不能使用这种格式的代码,因为它效率低下。使用for语句将为您带来更好的结果,因为循环会自动继续,同时增加索引值(在您的情况下为ij)。 range()函数返回一个数字序列,将其与for参数结合使用时,您可以创建一个循环

这就是您想要的:

for i in range(5):
    for j in range(5):
        print('Inner While Loop')
    print('Outer While Loop')