How to use yield to create generator in Python

Use yield statement

Fibonacci sequences using generators.


def fibonacci(max):
    a, b = 0, 1# from   ww w .j  a  v  a2  s . c  om
    while a < max:
        yield a
        a, b = b, a+b

for n in fibonacci(1000):
    print n,

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules