Fibonacci Sequence Using Recursion in Python

Fibonacci Sequence Using Recursion in Python

ECX 30 Days of Code and Design

Day 5

Fibonacci

Task:

Using recursion, write a function that prints out the first “n” members of the Fibonacci series. (The Fibonacci series is a series of integers, starting from 0 and 1, for which each term is the sum of the two-preceding terms (i.e. [0, 1, 1, 2, 3, 5, 8, 13, 21, ...] or “fib(n+1) = fib(n)+ fib(n-1)”.)

My Approach

First, we define our function, fibo(), which would take an integer as its parameter. We then check if the parameter is less or equal to one; if it is, it is returned as its output. If we have an integer above 1, the summation of (the number - 1) and (the number - 2) is returned. Next, we ask the user for the number of the sequence he wants to be printed. If he enters a number less than 0, we prompt him/her that we only want positive integers. When positive integers are entered, we create a for loop in the range of the number of the sequence the user wants, and the fibo() function is called the number of times the user inputted.

def fibo(n):

    if n <= 1:
        return n

    else:
        return fibo(n-1) + fibo(n-2)

print(“Fibonacci Series”)
num = int(input(‘Number of fibonacci series you want: ‘))

if num <= 0:
    print(‘Please, enter a positive integer.’)

else:
    for i in range(num):
        print(fibo(i), end=’ ‘)

When i = 0 and i = 1, the function prints back 0 and 1 respectively, because using if n <= 1:, we have programmed it to do so. When we have i = 2, we get; (2 – 1) + (2 – 2) = 1 + 0 = 1 When we have i = 3, we have; (3 – 1) + (3 – 2) = 2 + 1 = 3 We continue like that until the total number of sequences requested by the user is printed on the screen.

Output

If the user request to have the below output

Fibonacci Series
Number of Fibonacci series you want: 8
0 1 1 2 3 5 8 13

Run code on Replit