First we import from a small program, each set a list, find the prime number, we will write
Import Mathdef is_prims (number): if number = = 2: return True //All even numbers except 2 are not primes elif number% 2 = = 0: r Eturn False //If a number can be divisible by a number other than 1 and itself, then composite. In fact, our judgment range to square root n can be for cur in range (2,int (math.sqrt (number)) +1,2): If number% cur = = 0: return False else: return truedef get_prims (input_list): result_list = list () for element in Input_list: if Is_ Prims (Element): result_list.append (Element) return result_listaa = Get_prims ([1,2,3,4,5,6,7,8,9]) print ( Aa
But what if we want to give a number and then list all the primes that are larger than this number? We may write this:
def get_prims (number): if Is_prims (number): return number
But once the return function gives control to the caller and ends completely, any local variables and function work is discarded, and the next call starts again. So we can use the notation:
def get_prims (number): While (True): if Is_prims (number): yield number number + = 1def get_numbers (): Total = list () for Next_prim in Get_prims (2): if Next_prim <: Total.append (Next_prim) Else : print (total) returnget_numbers ()
Here's an explanation of the generator function, where the DEF code of a function contains yield, and the function automatically becomes a generator function (which still contains a return in time), and the generator function creates generator (a special kind of iterator, This iterator has a built-in next () method) that, when a value is needed, is generated instead of directly by yield, so unlike the general function, control is not surrendered at this time.
The For loop implicitly calls the next () function, and the next () function calls the next () method in generator, at which point the generator is responsible for returning a value to any method calling next (), using yield to pass this value back, equivalent to the return statement.