yield for python

本文深入探讨了Python中yield关键字的功能,通过示例代码展示了如何使用yield创建生成器函数,解释了生成器函数如何像迭代器一样工作,以及如何在函数执行过程中发送和接收值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

yield for python

a example of code

def fun():
    for i in range(20):
        x = yield i
        print('good', x, i)

if __name__ == '__main__':
    a = fun()
    a.__next__()
    a.__next__()
    x1 = a.send(5)
    x2 = a.send(3)
    next(a)
    next(a)
    print(x1, x2)

results

good None 0
good 5 1
good 3 2
good None 3
good None 4
2 3

description

yield generator functions allow you to declare a function that behaves like an iterator.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值