1

Why doesn't the very first iteration go to the first print statement. After all, isn't 2%2==0?

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4

2 回答 2

1

第一次通过循环,n = 2所以xrange(2, 2)其中是一个空列表。遍历空列表不会进入内部循环,但会执行else子句。

于 2013-06-13T15:58:34.100 回答
0

2 不在range(2, 2)。的上限range是独占的,所以它在到达它之前就停止了。

于 2013-06-13T16:00:42.223 回答