Home >Backend Development >Python Tutorial >Python uses an iterator to capture the return value of a Generator
This article mainly introduces the method of Python using iterators to capture the return value of Generator. It analyzes the related operation skills of Python iterator to obtain the return value of Generator based on specific examples. Friends in need can refer to it
The example in this article describes how Python uses iterators to capture the return value of Generator. Share it with everyone for your reference, the details are as follows:
When calling the generator using a for loop, I found that the return value of the generator's return statement cannot be obtained. If you want to get the return value, you must capture the StopIteration error. The return value is included in the value of StopIteration:
#!/usr/bin/env python # -*- coding: utf-8 -*- def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done' # 捕获Generator的返回值 g = fib(6) while True: try: x=next(g) print('g=',x) except StopIteration as e: print('Generrator return value:', e.value) break
Output:
g= 1 g= 1 g= 2 g= 3 g= 5 g= 8 Generrator return value: done
The above is the detailed content of Python uses an iterator to capture the return value of a Generator. For more information, please follow other related articles on the PHP Chinese website!