Javaexercise.com

Python Program to Generate Fibonacci Series

Fibonacci Series is a group of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The Fibonacci series starts from 0 and 1 and each next number is a sum of the previous two numbers.

For example, if we find a Fibonacci series of 7 numbers then the series would be like 0, 1, 1, 2, 3, 5, 8. Notice, each number is after 0 and 1 is sum of the previous two numbers. This is called the Fibonacci series and originally belongs to mathematics where it is represented as Fn.

Well, after understanding the concept of the Fibonacci series, let's implement it by using the Python language. So, we will create some Python programs to compute the Fibonacci series with the help of programming concepts like for-loop, while-loop, and recursion as well. 

 

Algorithm to Generate Fibonacci Series

Begin:

Step1: Create Three variables as f0, f1, and fab and initialize with 0, 1, 0 respectively

Step2: Create a variable n to hold the number of terms of Fibonacci Series

Step3: Start Loop:

Step4: Print fab variable

Step5: Assign f1 to f0

Step6: Assign fab to f1

Step7: Assign the sum of f0 and f1 to fab

Step8: Repeat Step3 to Step7 until the series reach to the n.

End:

 

 

Python Program to Create Fibonacci Series Using for Loop

# Python program to create fibonaci series
n = 8 # Numbers of terms for series
f0 = 0
f1 = 1
fab = 0
print("Fibonacci Series: \n")
for a in range(0,n):
  print(fab) # Print Series
  # Swapping values
  f0 = f1;
  f1 = fab;
  fab = f0+f1;

Output:

Fibonacci Series: 

0
1
1
2
3
5
8
13

 

Python Program to Create Fibonacci Series Using While Loop

# Python program to create fibonaci series
n = 8 # Numbers of terms for series
f0 = 0
f1 = 1
fab = 0
a = 0
print("Fibonacci Series: \n")
while a < n:
  print(fab) # Print Series
  # Swapping values
  f0 = f1;
  f1 = fab;
  fab = f0+f1;
  a+=1

Output:

Fibonacci Series: 

0
1
1
2
3
5
8
13

 

Python Program to Create Fibonacci Series Using Recursion

# Python program to create fibonaci Series
n = 8 # Numbers of terms for series
# Recursive Function to generate Fibonacci Series
def getFibonacci(number):
  if(number == 0):
    return 0
  elif(number == 1):
    return 1
  else:
    return (getFibonacci(number - 2) + getFibonacci(number - 1))

for a in range(0,n):
# Calling recursion function
  fab = getFibonacci(a)
  print(fab) # Print Series

Output:

Fibonacci Series: 

0
1
1
2
3
5
8
13

 

Python Program to Create Fibonacci Series Based on User Input

# Python program to create fibonaci Series
n = int(input("Enter a value : ")) # Numbers of terms for series
f0 = 0
f1 = 1
fab = 0
print("Fibonacci Series: \n")
for a in range(0,n):
  print(fab) # Print Series
  # Swapping values
  f0 = f1;
  f1 = fab;
  fab = f0+f1;

Output:

Fibonacci Series: 

0
1
1
2
3
5
8
13