def countdown( )print("counting down from %dnwhile yield - return if you call this functionyou will find that none of its code starts executing for examplec countdown( insteada generator object is returned the generator objectin turnexecutes the function whenever next(is called (or _next_ (in python here' an examplec next(counting down from next( use __next__(in python when next(is invokedthe generator function executes statements until it reaches yield statement the yield statement produces result at which point execution of the function stops until next(is invoked again execution then resumes with the statement following yield you normally don' call next(directly on generator but use it with the for statementsum()or some other operation that consumes sequence for examplefor in countdown( )statements sum(countdown( ) generator function signals completion by returning or raising stopiterationat which point iteration stops it is never legal for generator to return value other than none upon completion subtle problem with generators concerns the case where generator function is only partially consumed for exampleconsider this codefor in countdown( )if = break statements in this examplethe for loop aborts by calling breakand the associated generator never runs to full completion to handle this casegenerator objects have method close(that is used to signal shutdown when generator is no longer used or deletedclose(is called normally it is not necessary to call close()but you can also call it manually as shown herec countdown( next(counting down from next( close( next(traceback (most recent call last)file ""line in stopiteration lib fl ff