Fibonacci Series In Python

Fibonacci Series In Python

Published on October 28 2021

In this tutorial, you will learn how to write a Python program to print the Fibonacci series using a for loop.

So the first question comes to mind: what is the Fibonacci series

  • It is a sequence of integer numbers formed by the addition of preceding two numbers in the series.
  • It always starts from zero and one and then continues by the addition of preceding two numbers.

Example

0,1,1,2,3,5,8,13,21,34,55,89,144....

In the above example, 0 and 1 are the first two terms of the series. The third term is calculated by adding the first two terms, in this case 0 and 1.

0 + 1 = 1

So we get 0 + 1 = 1. Hence 1 is printed as the third term. 

The fourth term is calculated by adding the second and third term, i.e. 1 and 1

1 + 1 = 2

So 1 + 1 = 2, is the fourth term, and similarly it goes for the entire series.

Methods

We can print Fibonacci series in many ways:

  1. Using Loop
  2. Recursion
  3. Optimized technique etc.

In this tutorial, we will write code using Loop.

Code Explanation

  1. First, we need an integer input from the user using the input method and convert it to integer type using Int method. This number defines how many Fibonacci terms we want in Fiboseeries.
    num = int(input("Enter any number :"))
  2. First two numbers are always 0 and 1, so we can declare two variables.
    n1, n2 = 0, 1
  3. Fibonacci series is calculated by addition of preceding two numbers. So let's declare one variable sum, which will store our sum value, and let's set it to zero initially.
    sum = 0
  4. If the number entered by the user is 0 or < 0, then we can simply print some error message
    if num <= 0:
        print('Please enter number greater than 0')
  5. If the number is > 0, then we'll find the Febo series.
  6. To print n terms from the series, we'll write one for loop with a range function starting from 0 to num.
    else:
        for i in range(0, num):
    • First thing is to print the initial sum value. In the first occurrence the sum will be zero.
      print(sum, end=" ")
    • Next step is to interchange the variables so the 2nd number will be considered as 1st value and sum value will be considered as 2nd number
      n1 = n2
      n2 = sum
    • We can calculate sum as
      sum = n1 + n2

      It will perform the addition of preceding two numbers.

    • This process will continue until the condition is satisfied.

Source Code

# python program to print the Fibonacci series upto n terms

num = int(input("Enter any number :"))
n1, n2 = 0, 1
sum = 0
if num <= 0:
    print('Please enter number greater than 0')
else:
    for i in range(0, num):
        print(sum, end=" ")
        n1 = n2
        n2 = sum
        sum = n1 + n2

print('completed..')

Output

Enter any number :7
0 1 1 2 3 5 8