• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

2周前 (04-08) 6次浏览

# 【Python基础】函数：输出一个区间内的素数

## 判断质数

``````def Prime(i):
for a in range(2, i):
if i % a == 0:
break
if a == i - 1:
return i
``````

（注意，不是素数的时候的并不是没有返回值，有返回值，返回值为’none’,代表返回了个寂寞）

``````def Prime(i):
if i == 2:
return 2
for a in range(2, i):
if i % a == 0:
break
if a == i - 1:
return i
``````

## 输出区间内的素数

``````def Primes(n,m):
li=[]
for i in range(n,m):
li.append(Prime(i))
return li
``````

``````[None, 2, 3, None, 5, None, 7, None, None, None, 11, None, 13, None, None, None, 17, None, 19, None, None, None, 23, None, None, None, None, None, 29, None, 31, None, None, None, None, None, 37, None, None, None, 41, None, 43, None, None, None, 47, None, None, None, None, None, 53, None, None, None, None, None, 59, None, 61, None, None, None, None, None, 67, None, None, None, 71, None, 73, None, None, None, None, None, 79, None, None, None, 83, None, None, None, None, None, 89, None, None, None, None, None, None, None, 97, None, None]
``````

``````def Primes(n,m):
li=[]
for i in range(n,m):
if Prime(i) != None:
li.append(Prime(i))
return li
``````

## 综上所述

``````def Prime(i):
if i == 2:
return 2
for a in range(2, i):
if i % a == 0:
break
if a == i - 1:
return i
def Primes(n,m):
li=[]
for i in range(n,m):
if Prime(i) != None:
li.append(Prime(i))
return li

print('你想知道哪个区间中的全部素数？[n,m)')
n=int(input('n='))
m=int(input('m='))
print('区间[%d,%d)的所有素数为：'%(n,m),Primes(n,m))
``````

``````你想知道哪个区间中的全部素数？[n,m)
n=1
m=100

``````