Python while循环在超出范围(0,10)后不会终止,但是for循环会终止。这是为什么?

时间:2020-09-01 02:49:42

标签: python loops

如果我在下面的代码中使用while循环,它将永远不会继续打印我的列表“ Comm”,但是如果我只更改while,它将按预期工作—将所有常见的整数打印在shell的一行中。

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13]

x = 0

Comm = [] #common int in both lists

while x in range(0,len(a)):
    if a[x] in b:
        Comm.append(a[x])
        x += 1
print(Comm)

1 个答案:

答案 0 :(得分:1)

您应该使用for循环而不是while

如果x从0变为6,则a[6] = 13a[6]b中,因此x变成7,而a[7] = 21

a[7]不在b中,因此x不会增加。这意味着x停在7,并且不会脱离while循环。

相关问题