through sequence or value generatorif the protocol is supported (if notiteration falls back on repeatedly indexing sequences insteadany object that supports this interface works in all iteration tools to support this protocolfunctions containing yield statement are compiled specially as generators--they are not normal functionsbut rather are built to return an object with the expected iteration protocol methods when later calledthey return generator object that supports the iteration interface with an automatically created method named __next__ to start or resume execution generator functions may also have return statement thatalong with falling off the end of the def blocksimply terminates the generation of values--technicallyby raising stopiteration exception after any normal function exit actions from the caller' perspectivethe generator' __next__ method resumes the function and runs until either the next yield result is returned or stopiteration is raised the net effect is that generator functionscoded as def statements containing yield statementsare automatically made to support the iteration object protocol and thus may be used in any iteration context to produce results over time and on demand as noted in in python xiterator objects define method named next instead of __next__ this includes the generator objects we are using here in this method is renamed to __next__ the next built-in function is provided as convenience and portability toolnext(iis the same as __next__(in and next(in and prior to programs simply call next(instead to iterate manually generator functions in action to illustrate generator basicslet' turn to some code the following code defines generator function that can be used to generate the squares of series of numbers over timedef gensquares( )for in range( )yield * resume here later this function yields valueand so returns to its callereach time through the loopwhen it is resumedits prior state is restoredincluding the last values of its variables and nand control picks up again immediately after the yield statement for examplewhen it' used in the body of for loopthe first iteration starts the function and gets its first resultthereaftercontrol returns to the function after its yield statement each time through the loopfor in gensquares( )print(iend='resume the function print last yielded value generator functions and expressions