Lesson 3 of 7 · 10 min · 2 hands-on steps

Functions & the Call Stack

Write reusable functions and watch Python jump in and out of them.

Defining functions

Python · try it
def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Ada"))
print(greet("Ada", greeting="Welcome"))  # keyword argument

Watch the call stack

When a function calls another function, Python pauses the first one, runs the second, then comes back. That pile of "paused" functions is the call stack. Step through and watch the Call stack box:

Notice how w and h exist separately inside each function. Each call gets its own set of variables.

Returning several values

Python · try it
def min_max(nums):
    return min(nums), max(nums)

low, high = min_max([4, 9, 1, 7])
print(low, high)

Docstrings

Professional Python functions start with a short description:

Python · try it
def bmi(weight_kg, height_m):
    """Return body-mass index, rounded to 1 decimal."""
    return round(weight_kg / height_m ** 2, 1)

print(bmi(70, 1.75))
print(bmi.__doc__)

🧪 Practice: 2 steps

0 / 2 done

Step 1 of 2 · BMI calculator

Write bmi(weight_kg, height_m) that returns weight ÷ height², rounded to 1 decimal.

Python
def bmi(weight_kg, height_m):
    pass

Output appears here. Press Run or Ctrl/⌘ + Enter.

✅ Check your understanding

  1. What does a Python function return if it has no return statement?

Create a free account to track your progress.