Tag: value for loop [] break loop output encountered generator end USR
1 #!/usr/bin/env Python32 #-*-coding:utf-8-*-3 4 #01. What is a generator?5 #==> in Python, a mechanism that loops one side of the computation, called the generator: Generator6 " "7 in Python, a function that uses yield is called a generator (generator)8 Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and easier to understand .9 The generator is an iterator. Ten In the process of calling the generator to run, the function pauses and saves all current run information each time the yield is encountered, returning One the value of yield. and continue running from the current location the next time the next () method is executed. A " " - #02. How do I create a generator (generator)? - #to create a generator, the first method simply changes the [] form of a list-generated the #(), create a generator. -L = [x * x forXinchRange (10)]#List-generated - PrintL#[0, 1, 4, 9, +,- -s = (x * x forXinchRange (10))#Generator + Print(s)#<generator Object <genexpr> at 0x0000000002126888> - forXinchS#output Generator All elements with a for loop + Print(x,end=" ")#0 1 4 9 A Print("") at -S1 = (x * x forXinchRange (10)) - Print(List (S1))#convert a generator to a list - - deffib (max): -N, a, b = 0, 0, 1 in whileN <Max: - yieldb toA, B = B, A +b +n = n + 1 - return ' Done' the *f = fib (10) $ Print('fib (+):', F)Panax Notoginseng forXinchF: - Print(x,end=" ") the Print("") + A #Call Generator manually: theg = FIB (5) + while1: - Try: $x =Next (g) $ Print('g:', X) - exceptstopiteration as E: - Print('Generator return value:', E.value) the Break
Python Learning---Builder