Skip to Main Content

Python for Basic Data Analysis

Start your data science journey with Python. Learn practical Python programming skills for basic data manipulation and analysis.

What are recursive functions?

Recursive functions are functions that calls itself. It is always made up of 2 portions, the base case and the recursive case.

  • The base case is the condition to stop the recursion.
  • The recursive case is the part where the function calls on itself.

Let's use recursive functions to find the factorial of an integer. A factorial is the product of all integers from 1 to the number itself.

In the example below, we will be looking for the factorial of 4, or, 4!. 

Factorial of 4 is 4! = 1 * 2 * 3 * 4 = 24


Now let's analyse what is going on in the above recursive function.

  1. First, when we pass the integer 4 into the function, it goes to the recursive case return(x * factorial(x-1)) which will give us return(4 * factorial(3)).
     
  2. Next, the function will call factorial(3) which will give us return(3 * factorial(2)) and it goes on until we have x == 1 (the base case) and then the recursion will terminate. This means that if we do not have a base case to stop the recursion, the function will continue to call itself indefinitely.
     
  3. At the end we will have return(4 * 3 * 2 * 1)

Visualize how the codes work by clicking on the Next button below.

Video Guide

Activity 1

Write a recursive function that will sum all numbers from 1 to n. 

n is the argument of the function.

Activity 2 (Challenging)

Write a recursive function that will find the smallest number in a list.

Let the list be A = [1, 4, 24, 17, -5, 10, -22]

HINT: 

Use the min function in python