Python USES an iterator to capture the method of the return value of Generator

  • 2020-05-27 06:21:50
  • OfStack

This example shows how Python USES an iterator to capture the return value of Generator. I will share it with you for your reference as follows:

When calling generator with the for loop, the return value of generator's return statement is not found. If you want to get the return value, you must catch the StopIteration error, which is contained in 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'
#  capture Generator The return value of the 
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

For more information about Python, please check out the topics on this site: summary of Python function skills, Python data structure and algorithm tutorial, Python string manipulation skills summary, Python introduction and advanced classic tutorial, and Python file and directory manipulation skills summary.

I hope this article has been helpful to you in Python programming.


Related articles: