和朋友讨论一个简单的用Python实现求指定范围内的所有质数的问题:
教程给出的代码如下
M = input()
N=input()
M = int(M)
N = int(N)
X = []
for i in range(M,N+1):
for j in range(2,i):
if i%j == 0:
break
else:
X.append(i)
print(X)
会发现一个很奇特的,else语句居然和for对齐了,在映像中else是和if 搭配的。
首先让我们分析一下这个求质数算法的逻辑:
输入N和M,写一个for循环遍历,内容是对每一个确定的数进行质数判断:
质数判断部分:
输入为i,对于j = 2 , i-1 的所有的数进行一个遍历,这里我们就会考虑到用for 循环,进行操作i%j判断,如果能够整除,马上结束对质数判断的过程,这里我们用一个break就可以结束。
那么关键的点是:如何才能判断是一质数呢,也就是整除遍历都不满足之后,方可判断该数为质数。
在Python的文档中有关于for和else搭配的用法:
When the items are exhausted (which is immediately when the sequence is empty), the suite in the else clause, if present, is executed, and the loop terminates.
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
大意是说当迭代的对象迭代完并为空时,位于else的子句将执行,而如果在for循环中含有break时则直接终止循环,并不会执行else子句。