Python Fibonacci Generator Examples

Last Updated On Thursday 20th Jan 2022

Fibonacci sequence generator

The Fibonacci series is a classic series of numbers

  • where the 0th element is 0,
  • the 1st element is 1,
  • from there on, each element is the sum of the previous two elements.
  • For example, the following represents a Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 34, …

Example 1

	n = int(input('How many Fibonacci ?'))

f1=0
f2=1
c=2

if n == 1:
    print(f1)
elif n == 2:
    print(f1,'n',f2,sep='')
else:
    print(f1,'n',f2,sep='')
    while c < n:
        f = f1+f2
        print(f)
        f1=f2
        f2=f
        c=c+1
	

Input :10

	How many Fibonacci? 10
0
1
1
2
3
5
8
13
21
34
	

Example 2: Function with generators

	a = int(input('Number : '))

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

print(list(fibonacci(a)))
	

Input :8

	Number : 8
[0, 1, 1, 2, 3, 5, 8, 13]