PHP前端开发

Python使用迭代器捕获Generator返回值的方法

百变鹏仔 3小时前 #Python
文章标签 返回值

这篇文章主要介绍了python使用迭代器捕获generator返回值的方法,结合具体实例形式分析了python迭代器获取生成器返回值的相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python使用迭代器捕获Generator返回值的方法。分享给大家供大家参考,具体如下:

用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中:

#!/usr/bin/env python# -*- coding: utf-8 -*-def fib(max):  n, a, b = 0, 0, 1  while n <p></p><p>输出:</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><p class="jb51code"></p><pre class="brush:py;">g= 1g= 1g= 2g= 3g= 5g= 8Generrator return value: done