Unit 5 · Lesson 3

Scope & Variable Lifetime

Variables inside functions stay inside.

Distinguish local from global
Understand parameter locality
Avoid global pitfalls
Refactor for encapsulation

Local vs Global Scope

Variables inside a function are local:

x = 10 # global def my_func(): x = 20 # local — different x! print("Inside:", x) my_func() print("Outside:", x) # 10
Rule: Avoid global variables. Pass data in as parameters and get data out via return.
Practice Time

Challenges

🔍

Challenge 1: Scope Detective

Guided

Predict output of scoped code.

Instructions: Set answer1 (x after call), answer2 (result), answer3 (x+result).
Hint: Global x stays 5. result = 99. sum = 104.
🔢

Challenge 2: Counter Function

Guided

Mutable list as state.

Instructions: make_counter() returns [0]. increment(counter) adds 1 to counter[0], returns new value.
Hint: Lists are mutable! counter[0] += 1; return counter[0]
🐛

Challenge 3: Bug Hunt

Solo

Fix scope-related bugs.

Instructions: Fix the function to accept current total as a parameter and return the new total.
Hint: def add_to_total(current_total, amount): return current_total + amount
🏗

Challenge 4: Encapsulation

Stretch

Refactor globals into clean functions.

Instructions: Write create_player(name, score), add_points(player, points), get_info(player) using dicts.
Hint: create returns {"name":name,"score":score}. add_points returns new dict with updated score.