Python Program: Fibonacci Series

One of the most well-known series in Mathematics, the Fibonacci Sequence is a sequence where each term is a sum of the two preceding terms, starting from 0 and 1. The sequence is named after the famous Italian mathematician Leonardo Pisano who introduced it to the West in his book Liber Abaci composed in AD 1202.

Generally, the sequence is denoted by $F_{n}$ where $n \geq 0$. Hence,

$F_{0} = 0$, $F_{1} = 1$, and for values of $n > 1$,

$F_{n} = F_{n-1} + F_{n-2}$

The sequence starts as: 0, 1, 1, 2, 3, 5, 8, 13, ...

leonardo fibonacci Leonardo Fibonacci. Public Domain

Here is a simple Python program to print Fibonacci Numbers upto a given number of $n$ terms.

				
				n = int(input("Number = "))

				first = 0
				second = 1

				for i in range(0,n+1):
					if(i <=1):
						next = i
					else:
						next = first + second
						first = second
						second = next
					if(i < n):
						print(next,", ", end='')
					else: 
						print(next)
				
			

Below is the generated Fibonacci sequence upto $F_{7}$

python program fibonacci output

We can also construct a recursive function to print out Fibonacci Numbers as shown in the program below. We define a recursive function called fibonacci().

				
				n = int(input("Number = "))
				first = 0
				second = 1

				def fibonacci(m):
				   	if(m <= 1):
				   		return m
				   	else:
				   		return fibonacci(m-1)+fibonacci(m-2)

				for i in range(0,n+1):
					if(i < n):
						print(fibonacci(i),", ", end='')
					else:
						print(fibonacci(i))