首页 > 解决方案 > 素数程序中的范围函数

问题描述

这是一个打印从 2 到 11 的素数的程序。

for num in range(2,12):
    prime = True
    for i in range(2,num):
        if (num%i==0):
            prime = False
    if prime:
       print num

在最后一次迭代期间的第二个 for 循环中,num=11 的值 .. 所以范围应该取 num 为 10 即 (n-1) 但在这个程序中,值 11 仍然被打印出来 .. 那是怎么回事?

标签: pythonpython-2.7

解决方案


num is indeed 11, and it is num that is being printed:

if prime:
    print num

The range(2, num) range goes from 2 through to 10, inclusive, but the for loop over that range uses i as the target, not num:

for i in range(2, num):
#   ^  the target of the for loop

So it is the value of i, not num that goes from 2 through to 10, and i is never printed. The value of num is not changed by the inner loop, it remains set to 11 all the way through. So yes, it'd be surprising if 10 was printed instead.

Note that the print num line is only ever executed if prime is still set to True. It would be set to False if num was divisible by any of the i values. For 11, there is no value between 2 and 10 (inclusive) that can divide 11, so prime remains set to True and num is printed.


推荐阅读