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
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ada"))
print(greet("Ada", greeting="Welcome")) # keyword argumentWatch 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
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:
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 doneStep 1 of 2 · BMI calculator
Write bmi(weight_kg, height_m) that returns weight ÷ height², rounded to 1 decimal.
def bmi(weight_kg, height_m):
pass
Output appears here. Press Run or Ctrl/⌘ + Enter.
Step 2 of 2 · Keyword arguments
Write format_price(amount, currency="$", decimals=2) that returns e.g. "$9.99", and format_price(5, currency="€", decimals=0) → "€5".
def format_price(amount, currency="$", decimals=2):
pass
Output appears here. Press Run or Ctrl/⌘ + Enter.
✅ Check your understanding
What does a Python function return if it has no return statement?
Create a free account to track your progress.