Skip to Main Content
It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

Python for Basic Data Analysis: 2.7 Recursive Functions

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of 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.

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]


Use the min function in python