Menu
Coddy logo textTech

Recursive Functions Part 1

Part of the Logic & Flow section of Coddy's Python journey — lesson 60 of 78.

A recursive function is a function that calls itself to solve smaller instances of a problem. Each recursive call must bring the function closer to a base case, which stops the recursion.

Example: Summing numbers from 1 to n:

def sum_to_n(n):
    if n == 0:  # Base case
        return 0
    return n + sum_to_n(n - 1)  # Recursive step

print(sum_to_n(5))  # Output: 15
challenge icon

Challenge

Easy

Write a recursive function named count_down that takes a positive integer n as an argument and prints each number from n down to 0.

Cheat sheet

A recursive function calls itself to solve smaller instances of a problem. Each recursive call must bring the function closer to a base case, which stops the recursion.

Basic structure:

def recursive_function(parameter):
    if base_case_condition:  # Base case
        return base_value
    return recursive_step  # Recursive step

Example - summing numbers from 1 to n:

def sum_to_n(n):
    if n == 0:  # Base case
        return 0
    return n + sum_to_n(n - 1)  # Recursive step

print(sum_to_n(5))  # Output: 15

Try it yourself

def count_down(n):
    # Write code here
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow