Skip to content
← Python for AI/ML · all 50 levels

Recursion

Level 41 of 50 · Functions

Level 41 of 50

Recursion

a function that calls itself. Watch the reel, then work through it below: run the code, take the quiz, keep the cheat sheet.

📒 Open the cheat sheet
SanaThree, two, one... Iftar! Everyone at the table counts down!
TeacherA countdown is one step, repeated. A function calling itself: recursion!
iftar.py
def countdown(n):
    if n == 0:
        print("Iftar!")
        return
    print(n)
    countdown(n - 1)

countdown(2)
Teachercountdown prints n, then calls itself with n - 1!
SanaCalling itself? Won't it run FOREVER?
TeacherNot with a base case! When n hits 0, it stops!
oops.py
def again():
    again()

again()
TeacherNo base case? Python gives up with a RecursionError!

⏸ Pause & predict: what prints?

def total(n):
    if n == 1:
        return 1
    return n + total(n - 1)

print(total(3))

Where this leads

Python is step one. Building AI that ships is the rest.

The diploma takes you from zero to deployed computer vision, LLM and agent projects, with engineers who build them for a living. Already code? The bootcamp does it in three months.