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:
    print(one)
elif inp == 2:
    print(two)
# generate sequence using while loop.
else:
    print('Fibonacci series.')
    while curr < inp:
        print(one)
        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.
0
1
1
2
3

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):
        return
    print(one)
    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:
0
1
1
2
3

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!