How to Implement a Fibonacci Sequence in Python
How to Implement a Fibonacci Sequence in Python

How to Implement a Fibonacci Sequence in Python

If you're invited for a coding interview, one of the classic questions you might be asked is how would you code a Fibonacci series? For obvious reasons, you'll first need to know what's a Fibonacci series before you can implement the solution. Then you'll need to decide which language you will use to implement the solution. Let's first with a simple definition of the Fibonacci series and later we will focus on its implementation using Python. 

What is a Fibonacci Sequence?

The Fibonacci Sequence (Fn) is the series of numbers such that each number is calculated by adding the sum of the two numbers before it, with the first two terms being 0 and 1.

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

From a mathematical standpoint, the Fibonacci Sequence is defined by a recurrence relation and is defined using the following rule. 

                                                    F(n) = F(n1) + F(n2)

where:

  • F(n) is the term number “n”
  • F(n-1) is the previous term (n-1)
  • F(n-2) is the term before that (n-2)

So let's implement the Fibonacci Sequence using the recursive formula in Python. Before you dive in you'll need to understand the following programming concepts in Python.

  • if statements
  • for loops
  • functions
  • recursion
def fib_recursive(n):
    if n <= 1:
        return n
    else:
        return (fib_recursive(n-1) + fib_recursive(n-2))

no_terms = 14

#check n<0
if no_terms < 0:
    print("Invalid input, please enter a positive integer.")
else:
    print("The first 14 terms of Fibionacci Sequence are as follows." )
    for i in range(no_terms):
       print(fib_recursive(i)) 

Output 



The first 14 terms of Fibionacci Sequence are as follows.
0
1
1
2
3
5
8
13
21
34
55
89
144
233

Keep the momentum going in preparation for your interview and check out my article on the four pillars of Object-Oriented Programming here.

Published By
Kadian Davis-Owusu (PhD)
Kadian has a background in Computer Science and pursued her PhD and post-doctoral studies in the fields of Design for Social Interaction and Design for Health. She has taught a number of interaction design courses at the university level including the University of the West Indies, the University of the Commonwealth Caribbean (UCC) in Jamaica, and the Delft University of Technology in The Netherlands. Kadian also serves as the Founder and Lead UX Designer for TeachSomebody and is the host of the ExpertsConnect video podcast. In this function, Kadian serves to bridge the learning gap by delivering high-quality content tailored to meet your learning needs. Moreover, through expert-collaboration, top-quality experts are equipped with a unique channel to create public awareness and establish thought leadership in their related domains. Tune in for weekly episodes of this podcast!... Show more
Comment