Course outline · 0% complete

0/32 lessons0%

Course overview →

Scope and Decomposing Problems

lesson 8-3 · ~12 min · 26/32

Scope: variables live where they are made

In a program with dozens of functions, names would collide constantly if every variable were visible everywhere: two functions both using total would silently corrupt each other. Scope is the isolation rule that prevents that, and it is what makes a function readable on its own, without studying the rest of the file.

A variable created inside a function, including its parameters, is local: it exists only while that call runs, then vanishes. The world outside never sees it.

n = 10
def show(n):
    n = n + 1
    print("inside:", n)

show(100)
print("outside:", n)   # still 10

The n inside is a different variable that merely shares the name. This isolation is a feature: a function cannot accidentally trample your other variables, and you can read it without knowing the rest of the program.

Rule of thumb for now: functions take what they need as parameters and hand results back with return. Reaching out to touch outside variables makes code hard to trace.

Code exercise · python

Run the scope demo. The function receives 100, changes its own local n, and the outside n never notices.

Decomposition: small functions, composed

Big problems fall apart into function-sized pieces. Grading a student is really two steps you already know: the average from lesson 6-3 and the letter chain from lesson 4-1. Give each a name:

def average(nums):
    return sum(nums) / len(nums)

def letter(avg):
    if avg >= 90:
        return "A"
    ...

Now the top level reads like the plan: letter(average(scores)). Each piece can be tested alone, reused, and fixed without touching the others. This is the single most important habit the mini-projects in unit 10 will demand.

Code exercise · python

Your turn. Complete both functions: `average(nums)` returns the mean, `letter(avg)` returns A (90+), B (80+), C (70+), or F. Then the given lines print the average to 1 decimal and the letter.

Problem

Trace by hand. What does this print? ```python def mystery(a, b): if a > b: return a - b return b - a print(mystery(3, 8)) ```