yield in python

yield in python,第1张

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/714262.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-24
下一篇 2022-04-24

发表评论

登录后才能评论

评论列表(0条)

保存