from math import *
def p():
for a in range (2, 100): ##for a in range 2 to 100
for y in range (2, a): ##for y in range 2, 100
x = 2*a+1 ##x has the following value
myprimelist = [] ##creating my empty list
if x > y:
while (x % y != 0):
myprimelist.append(x) ##append to list and continue with the same y until modulo is zero after which it reaches to else
y += 1
print (x,'nu se imparte egal la',y)
return [y] ##change the y
else:
y += 1
return [y]
else:
a += 1
return[a]
a += 1
return[a]
print (myprimelist);
我正在尝试制作一个能告诉我所有素数从2到100的函数,但由于某种原因,循环停止,我不知道为什么。请帮忙。谢谢!
答案 0 :(得分:2)
return
表示功能结束。每次遇到它时,该功能都会停止执行。
答案 1 :(得分:0)
它与python 3无关,它与return语句有关。您可以尝试以下代码,因为它只检查从1到sqrt(n),因为它没有必要尝试检查大于sqrt(n)的数字。希望这会有所帮助。
import math
for num in range(1,101):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print num