#!/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
Determine whether a number n is a prime number:
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 returnsTrue
. So it is outside the loop, not inside.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 returnFalse
immediately. If the for loop body has finished running, no number that can be divided evenly has been found. , this means that thisn
is a prime number, soreturn 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
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.