Let’s see with an example:
# of yield
# A generator function that yields 1 for first time,
# 2 second time and 3 third time
def simpleGeneratorFun():
yield 2
yield 3
for value in simpleGeneratorFun():
2
3
Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function.
# to 100 using yield and therefore generator
# An infinite generator function that prints
# next square number. It starts with 1
def nextSquare():
# An Infinite loop to generate squares
while True:
i += 1 # Next execution resumes
# from this point
# function
for num in nextSquare():
4
9
16
25
36
49
64
81
100