代码
# 求10以内的素数,质数:方法1 num1=[] for i in range(2,10): #质数不为0,1 所以范围从2起 for j in range(2,i): if i%j==0: break #能被比它小的数整除,则break else: #不能被比它小的数整除,则执行else,把这个数添加到列表中 num1.append(i) #[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] print(num1) # 求10以内的素数,质数:方法2 num11 = [x for x in range(2,10) if not [y for y in range(2,x) if x%y == 0]] print(num11) # 求10以内的素数,质数:方法3 import math num2 = [] for i in range(2,10): for j in range(2,int(math.sqrt(i)+1)): #math.sqrt(i):i的平方根 if (i%j==0): break else: num2.append(i) print(num2) # 求10以内的素数,质数:方法4 num22 = [x for x in range(2,10) if not [y for y in range(2,int(math.sqrt(x))+1) if x%y == 0]] print (num22)
结果
[2, 3, 5, 7] [2, 3, 5, 7] [2, 3, 5, 7] [2, 3, 5, 7]