ALL MODULESmodule_07.py

Functions, Scope & Recursion

~60 minTheoryLive CodingChallengeQuiz
theory.md

7. Functions, Scope & Recursion

7.1Reusable Blocks of Code (Functions)

Think of a microwave preset button — pressing "Popcorn" runs a saved set of cooking steps without you having to re-type the time and power every single time.

SHOW:

PYTHON
WHAT HAPPENED HERE
We defined a function named greet using def. Then we called it twice with different names, running the same code block with different inputs.
THE TECHNICAL NAME
A named block of reusable code is a function. The variable inside parentheses (name) is a parameter.
TAKEAWAY
Define reusable code with def function_name(parameter):.

7.2Returning Values

Think of an ATM machine — you enter your card and PIN, and the machine processes the request and hands back cash to you.

SHOW:

PYTHON
WHAT HAPPENED HERE
The return keyword sent the calculated answer (40) back out of the function so we could store it in variable total.
THE TECHNICAL NAME
The value sent back by a function is its return value. The code that ran the function is the caller.
TAKEAWAY
Use return to send a calculation back to your main program.

7.3Variable Scope (Local vs Global)

Think of a bedroom light switch vs a house main breaker — the bedroom switch only controls lights inside that specific room.

SHOW:

PYTHON
WHAT HAPPENED HERE
tax_rate is accessible anywhere because it was created outside. total was created inside calculate_price and only exists inside that function.
THE TECHNICAL NAME
Where a variable can be seen and used is its scope. Variables created inside functions have local scope.
TAKEAWAY
Variables created inside a function are local and cannot be accessed outside it.

7.4Recursion (Functions Calling Themselves)

Think of Russian Matryoshka dolls — opening one doll reveals a smaller doll inside, until you reach the smallest solid doll that stops the sequence.

SHOW:

PYTHON
WHAT HAPPENED HERE
countdown printed 3 and then called countdown(2), which printed 2 and called countdown(1). When n <= 0, it printed "Blast off!" and stopped calling itself.
THE TECHNICAL NAME
A function that calls itself is recursive. The condition that stops recursion is the base case.
TAKEAWAY
Recursion means a function calls itself — always include a base case to stop it!
GOTCHA 1

Forgetting a return statement when a function result is needed (functions implicitly return None).

GOTCHA 2

Forgetting a base case in a recursive function, causing a RecursionError (stack overflow).

GOTCHA 3

Attempting to modify a global variable inside a local scope without declaring it with global.

WHERE THIS SHOWS UP IN REAL CODE

Web APIs use functions to process user requests, while recursive algorithms traverse file directories and search nested category trees.

TRY THIS YOURSELF

Define a function double(n) returning n * 2 and call it with double(5).

live_coding — Interactive Factorial & Discount Calculator

Observe how recursive_factorial multiplies n by recursive_factorial(n - 1) until n <= 1.

Function Call Stack

argsvalueCallerFunction()ExecuteReturnResume Caller
Python not loaded yet.
demo — Demonstrate function parameters, return values, variable scope, and recursive call stack.

Demonstrate function parameters, return values, variable scope, and recursive call stack.

challenge_1

Warm-up 1: Define a greeting function.

Steps:

  1. Define function welcome(name).
  2. Print Welcome, Alex!.
  3. Call welcome("Alex").
Python not loaded yet.
challenge_2

Warm-up 2: Write a square function with return.

Steps:

  1. Define function square(num) returning num * num.
  2. Call square(4) and print Square: 16.
Python not loaded yet.
challenge_3

Warm-up 3: Recursive countdown function.

Steps:

  1. Define rec_count(n).
  2. Base case: if n <= 0 print Done! and return.
  3. Otherwise print n and call rec_count(n - 1).
  4. Call rec_count(2).
Python not loaded yet.
challenge_4

Apply-it 1: Calculate total order price with tax parameter.

Steps:

  1. Define calc_total(price, tax=0.08) returning price * (1 + tax).
  2. Call calc_total(100) and print Total: $108.00.
Python not loaded yet.
challenge_5

Apply-it 2: Find maximum of two numbers function.

Steps:

  1. Define function max_num(a, b).
  2. Return a if a > b else return b.
  3. Call max_num(15, 42) and print Max: 42.
Python not loaded yet.
challenge_6

Apply-it 3: Recursive sum of numbers from 1 to n.

Steps:

  1. Define recursive function rec_sum(n).
  2. Base case: if n <= 1 return 1.
  3. Recursive case: return n + rec_sum(n - 1).
  4. Call rec_sum(4) and print Recursive Sum: 10.
Python not loaded yet.
challenge_7

Stretch Challenge: Explain Recursion & Calculate Fibonacci.

Steps:

  1. Print explanation: Recursion is a function calling itself until hitting a base case..
  2. Define recursive fib(n) (base case: if n <= 1 return n, recursive: fib(n-1) + fib(n-2)).
  3. Call fib(6) and print Fib(6): 8.
Python not loaded yet.
quiz — 9 questions
30s question timers are paused. Start individually or all together.
# question 1

What keyword is used to define a function in Python?

# question 2

What happens if a Python function does not contain an explicit `return` statement?

# question 3

What is a parameter in a function definition?

# question 4

What is variable scope in Python?

# question 5

Can code outside a function directly access a local variable defined inside that function?

# question 6

What is recursion?

# question 7

What is the purpose of a base case in a recursive function?

# question 8

What error is raised if a recursive function lacks a base case?

# question 9

In `def greet(name='Guest'):`, what is `'Guest'` called?

discussion

# comments · functions-recursion

  • @priya · 2h ago

    The typewriter hero is such a nice touch.

    • @alex · 1h ago

      Totally agree! Made it super engaging.

  • @sam · 1d ago

    Finally a course where I can run code without leaving the page.