Company-Specific Courses
Free Resources
Webinars
About Us

Edit
Reply




Edit

Fibonacci Series In Python | Python Program To Print Fibonacci Series

Published on 09 Feb 2021


In this article, we will learn how to write Python Programs to generate the Fibonacci series until the given input value using two different methods. Fibonacci series is a series in which each number is the sum of the preceding two numbers. By default, the first two numbers of a Fibonacci series are 0 and 1.


fibonacci deries in Python



´╗┐INPUT FORMAT:

Input consists of an integer

OUTPUT FORMAT:

A single line of output containing the Fibonacci series until 7 values.


SAMPLE INPUT:

7

SAMPLE OUTPUT:

0 1 1 2 3 5 8

PREREQUISITE KNOWLEDGE:while loop in Python and Recursion in Python


Method 1:Using a while loop


Algorithm for printing Fibonacci series using a while loop


Step 1:Input the 'n' value until which the Fibonacci series has to be generated

Step 2:Initialize sum = 0, a = 0, b = 1 and count = 1

Step 3:while (count <= n)

Step 4:print sum

Step 5:Increment the count variable

Step 6:swap a and b

Step 7:sum = a + b

Step 8:while (count > n)

Step 9:End the algorithm

Step 10:Else

Step 11:Repeat from steps 4 to 7


Python program to print Fibonacci series until 'n' value using while loop


#Python program to generate Fibonacci series until 'n' value
n = int(input("Enter the value of 'n': "))
a = 0
b = 1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
  print(sum, end = " ")
  count += 1
  a = b
  b = sum
  sum = a + b

Input:

Enter the value of 'n': 5

Output:

Fibonacci Series: 0 1 1 2 3


Method 2: Using recursion


Recursive function algorithm for printing Fibonacci series


Step 1:If 'n' value is 0, return 0

Step 2:Else, if'n'value is 1, return 1

Step 3:Else, recursively call the recursive function for the value (n - 2) + (n - 1)


Python program to print Fibonacci series until 'n' value using recursion


#Python program to generate Fibonacci series Program using Recursion
def Fibonacci_series(Number):if(Number == 0):
    return 0elif(Number == 1):
    return 1else:
    return (Fibonacci_series(Number - 2) + Fibonacci_series(Number - 1))

n = int(input("Enter the value of 'n': "))
print("Fibonacci Series:", end = ' ')
for n in range(0, n):
  print(Fibonacci_series(n), end = ' ')

Input:

Enter the value of 'n': 5

Output:

Fibonacci Series: 0 1 1 2 3


Also refer:Fibonacci series of a number in C, C++ and Java




If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in
Explore 'python'
Articles