In this post we learn how to print fibonacci sequence but before writing program we should know what is fibonacci number?

Table of Contents

## What is fibonacci numbers?

First two number is fixed that is 0,1 and sum of previous two number will give next number and those number sequence is known as fubonacci numbers.

We should write this program in two  different ways

1. Using function
2. Using Recursive function

## 1. Fibonacci numbers Using function

Write a python program to print fibonacci numbers using function.

before writing this program we should know :

so let’s write a program for fibonacci numbers and see the output.

Source code:

``````# 0 1 1 2 3 5 8 13 ...
# a b c
#   a b c
#     a b c

def fibonacci(num):
a = 0
b = 1
if num == 1:
print(a, end=" ")
elif num == 2:
print(a,b)
else:
print(a, end=" ")
print(b, end=" ")
i = 0
while i < num-2:
c = a + b
a=b
b=c
print(c, end = " ")
i+=1
# return c
n = int(input("enter number for series :"))

fibonacci(n)``````

Output-1:

``````enter number for series :10
0 1 1 2 3 5 8 13 21 34``````

Output-2:

``````enter number for series :20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 ``````

## Explanation

NOTE: all the bold letter or words are function or variable name.

variable a = 0 and b = 1 are fixed then in c variable sum of next number is stored that is (c = a+b).

after that update a value of a and b —–> (a = b and b = c)

## 2.Fibonacci numbers Using Recursive function

Write a program to print fibonacci numbers using recursive function.

before writing this you should know:

1. about function
2. about recursive function
3. while loop
4. if-elif

Source code:

``````def fibo(n):
a = 0
b = 1
if n == 0:
return a
elif n == 1:
return b
else:
return fibo(n-1) + fibo(n-2)

n = int(input('ENter a number: '))
l = [str(fibo(i)) for i in range(0,n)]
# print(l)

print(','.join(l))``````

Output-1:

``````ENter a number: 11
0,1,1,2,3,5,8,13,21,34,55,89``````

Output-2:

``````ENter a number: 15
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377``````

Hope this post add sum value to your life -thankyou.

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.