I'm trying to learn python by reading the Learning Python book, and stumbled upon the section on using return expressions in generators, and it's hard for me to wrap my head around it.
It says that when using the return in a generator function, it will throw a StopIteration exception that must be raised, which actually ends the iteration. If the return actually returned something to the function, it would violate the iterative protocol.
Here is a sample code
def geometric_progression(a, q): k = 0 while True: result = a * q**k if result <= 100000: yield result else: return k += 1 for n in geometric_progression(2,5): print(n)
Can someone explain this, as well as how to use it further in any other context. Give more examples if you can.
phawk source share