Python Program to Print the Fibonacci Sequence (2 ways)
In this program, we will learn how to make a python program to print the Fibonacci Sequence. We will be learning two ways to make this program.
- Printing Fibonacci Sequence using loop
- Printing Fibonacci Sequence using Recursion
So, Let’s discuss these two ways one by one.
Printing Fibonacci Sequence
using Loop
We will be using the for loop here.
Code:-
# enter the number of terms of fibonacci sequence to print n = int(input("Enter a number: ")) # stores the previous value pre = 0 # stores the current value cur=1 # loop to print n terms of fibonacci sequence for i in range(1,n+1): # prints the current value print(cur,end=" ") # stores the current value to temp variable temp=cur # changes the current value by adding the prvious value to itself cur = cur + pre # changes the previous value to temp value pre = temp
Output:-
1 1 2 3 5 8 13 21 34 55
using Recursion
Now, we will see how to make this program using Recursion.
Code:-
# Recursive function for fibonacci sequence def fib(n): if n <=1: # Base Case return n else: # Iterative case return fib(n-1) + fib(n-2) # enter the number of terms of fibonacci sequence to print n = int(input("Enter a number: ")) # calling recursive fib function for i in range(n): print(fib(i),end=" ")
Output:-
1 1 2 3 5 8 13 21
You can learn about many other Python Programs Here.
Best Books for learning Python with Data Structure, Algorithms, Machine learning and Data Science.
Amit Rawat
Latest posts by Amit Rawat (see all)
- Python Program to Print the Fibonacci Sequence (2 ways) - April 7, 2020
- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019