Write a program to print the Fibonacci series in python.

The Fibonacci series is a series of Fibonacci numbers. These Fibonacci numbers have the most practical uses in the history of mathematics.

In this article, we are going to learn how to generate a Fibonacci series with a length of a given number.

Fibonacci series in python using a loop

# take input.
inp = int(input('Enter how many numbers in series you want? '))

# variables.
one, two = 0, 1
curr = 0

# return first term if inp is 1.
if inp == 1:
elif inp == 2:
# generate sequence using while loop.
    print('Fibonacci series.')
    while curr < inp:
        temp = one + two
        one = two
        two = temp
        curr += 1

The output of the above Fibonacci series program is

$python fibonacciseries.py
Enter how many numbers in series you want? 5
Fibonacci sequence.

The above program starts by taking an integer input value and then runs with the initial two numbers. Below is the formula for the Nth Fibonacci number.

# Formula for Nth Fibonacci number.
F(n) = F(n-2) + F(n-1)

From the 2nd iteration in the loop, we use the above formula and generate its associated Fibonacci number. In the same loop, we print the number as well which gives us a sequence of Fibonacci numbers.

Fibonacci series in python using recursion

def print_fibonacci(inp, curr, one, two):
    if(curr == inp):
    print_fibonacci(inp, curr+1, two, one+two)

print('Fibonacci series (length 5) using recursion:')
print_fibonacci(5, 0, 0, 1)

The output of the above program

$python fibonacciseriesrecur.py
Fibonacci series (length 5) using recursion:

Literally, we are using the above Nth Fibonacci number formula to generate the next Fibonacci number in the series. Hope this helps you to start learning python with the Fibonacci series using loops and recursion.

Happy learning!


Trie Data Structure

Trie data structures are useful to process and search in large character data sets. It takes only orders of word length to search a word in length file or a million words dictionary. Some examples where Trie’s use. In finding words in large files. In finding any word in the large dictionary of words. InRead More »

Clone given Graph

Given a graph with an adjacency list, we aim to clone the complete graph with edges. Cloning does creates a new memory for similar data. Let us understand this with a three-node example graph. We can solve this problem using either DFS or BFS. Let’s solve this problem using DFS. Our Graph object contains theRead More »