python中yield_使用Python中的示例的yield关键字

python中yield

Python yield关键字 (Python yield keyword)

yield is a keyword (case-sensitive) in python, it is used to suspend the execution of a function and returns the value, if next time function calls, it resumes the function execution from the next statement where last execution was suspended.

yield是python中的一个关键字(区分大小写),用于暂停函数的执行并返回值,如果下次调用函数,它将从上次执行被暂停的下一条语句恢复函数执行。

Note: return keyword and yield keywords returns the value to the called function, but the return statement terminates the execution of the function, while yield statement just suspends the execution of the programs.

注意: return关键字yield关键字将值返回给被调用的函数,但是return语句终止函数的执行,而yield语句只是挂起程序的执行。

Syntax of yield keyword

yield关键字的语法

    def function_name():
	    statement(s):
	    yield value
	    statement(s)

Example:

例:

    def sampleGenerate():
        yield 100
        yield 500
        yield 800

收益关键字的Python示例 (Python examples of yield keyword)

Example 1: Demonstrate the example with yield keywords by returning values multiple times on function calls.

示例1:通过在函数调用中多次返回值,来演示带有yield关键字的示例。

# python code to demonstrate example of 
# yield keyword

def sampleGenerate():
    yield 100
    yield 500
    yield 800

# main code
for value in sampleGenerate():
    print(value)

Output

输出量

100
500
800

Example 2: Find the squares of the numbers till a given maximum value of the square from main function.

示例2:从主函数中找到数字的平方,直到平方的给定最大值。

# python code to demonstrate example of 
# yield keyword

def generateSquare():
    count = 1
    while True:
        yield count*count
        count += 1  # next function execution
                    # resumes from here

# main code
for i in generateSquare():
    print(i)
    if i>=100:
        break

Output

输出量

1 
4 
9 
16
25
36
49
64
81
100


翻译自: https://www.includehelp.com/python/yield-keyword-with-example.aspx

python中yield

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值