Iterator captures python code example of Generator return value

Y2J
Release: 2017-04-27 11:53:23
Original
1496 people have browsed it

This article mainly introduces the method of Python using iterators to capture the return value of Generator. It analyzes the related operating 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 &#39;done&#39;
# 捕获Generator的返回值
g = fib(6)
while True:
  try:
    x=next(g)
    print(&#39;g=&#39;,x)
  except StopIteration as e:
    print(&#39;Generrator return value:&#39;, e.value)
    break
Copy after login

Output:

g= 1
g= 1
g= 2
g= 3
g= 5
g= 8
Generrator return value: done
Copy after login

The above is the detailed content of Iterator captures python code example of Generator return value. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template