#!/usr/bin/python
# -*- coding: UTF-8 -*-
import math
L = range(0,101)
def isprime(n):
if n<= 1:
return False
for i in range(2,int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True **# 这个return为什么要放到for的下面?为什么不放到 if n % i == 0 下面?**
y = filter(isprime, L )
print y
女神的闺蜜爱上我2017-06-12 09:26:00
Determine whether a number n is a prime number:
从 2 到 sqrt(n):
存在一个 n 为因数,不为素数,返回 False
不存在,为素数,返回 true
So, return True
is when it is judged that every number from 2 to sqrt(n) is not a factor, it is a prime number, and returns True
. So it is outside the loop, not inside.
阿神2017-06-12 09:26:00
Because if in the for loop body, if a number that can be divided evenly is found, it means that this n
is not a prime number, and it will return False
immediately. If the for loop body has finished running, no number that can be divided evenly has been found. , this means that this n
is a prime number, so return True
needs to be placed under for.
In addition, you can refer to the ideas in my blog: Python prints prime numbers within a certain value
扔个三星炸死你2017-06-12 09:26:00
If you return in the loop body, the loop will be terminated and returned when it encounters the first n % i != 0 number. There is no way to verify whether n is not divisible by every number within 100 (except 1 and itself), so return needs to be in the loop in vitro.