if表达式计算为False,但无论如何都会执行

时间:2013-11-09 13:17:14

标签: if-statement python-3.x boolean

for i in range(6, 21):
for y in range(len(lst)):
    if i % lst[y] != 0 and i % 2 != 0 and i % 3 != 0 and i % 5 != 0 and i != lst[-1]:
        lst.append(i)
        print(lst)

输出结果为:

[2, 3, 5, 7, 7, 7, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 7]
[2, 3, 5, 7, 7, 7, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 7, 11]
[2, 3, 5, 7, 7, 7, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 7, 11, 13]
[2, 3, 5, 7, 7, 7, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 7, 11, 13, 17]
[2, 3, 5, 7, 7, 7, 11, 11, 11, 11, 11, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19,    19, 19, 19, 19, 19, 19, 7, 11, 13, 17, 19]

所以,对于第二个七:7%3!= 0(TRUE)和i%2,3,5!= 0(TRUE)和i!= lst [-1](7!= 7 - > FALSE),为什么列表附加第二个七?

1 个答案:

答案 0 :(得分:1)

您的代码,具有固定缩进和初始值lst

lst=[2,3,5]
for i in range(6, 21):
    for y in range(len(lst)):
        if i % lst[y] != 0 and i % 2 != 0 and i % 3 != 0 and i % 5 != 0 and i != lst[-1]:
            lst.append(i)
            print(lst)

给我:

[2, 3, 5, 7]
[2, 3, 5, 7, 11]
[2, 3, 5, 7, 11, 13]
[2, 3, 5, 7, 11, 13, 17]
[2, 3, 5, 7, 11, 13, 17, 19]

您确定要在问题中发布相同的代码吗?