为什么该程序打印12?

时间:2020-08-15 19:23:17

标签: python break

for num in range(10,14):
    for i in range(2, num):
        if num%i == 1:
            print(num)
            break

该程序的输出为: 10 11 12 13

我对输出为何包含12感到困惑?因为当num = 12时,内部循环中i的值均不满足​​if条件。那么输出不应该排除12吗?你能解释为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

让我们简单地调试一下,您具有以下值:

num    i    num%i                   output
10     2        0 => do nothing  <nothing>
10     3        1 => print(num)         10
11     2        1 => print(num)         11
12     2        0 => do nothing  <nothing>
12     3        0 => do nothing  <nothing>
12     4        0 => do nothing  <nothing>
12     5        2 => do nothing  <nothing>
12     6        0 => do nothing  <nothing>
12     7        5 => do nothing  <nothing>
12     8        4 => do nothing  <nothing>
12     9        3 => do nothing  <nothing>
12    10        2 => do nothing  <nothing>
12    11        1 => print(num)         12
13     2        1 => print(num)         13

您现在了解逻辑了吗?