definition:
Yield is a keyword in Python that is used to return from a function without destroying the states of its local variable
and when the function is called, the execution starts from the last yield statement.
Any function that contains a yield keyword is termed a generator.
Hence, yield is what makes a generator.
demo
# A Python program to generate squares from 1
# to 100 using yield and therefore generator
# An infinite generator function that prints
# next square number. It starts with 1
def nextSquare():
i = 1
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
# Driver code
for num in nextSquare():
if num > 100:
break
print(num)
for num in nextSquare():
if num > 100:
break
print(num)
output
wk@ubuntu:~/workspace/pdir$ python yield.py
1
4
9
16
25
36
49
64
81
100
1
4
9
16
25
36
49
64
81
100
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)