Legends ofPythos
Claim your name
Writing Real Programs

Scope: where variables live

Lesson 6 of 16

Watch the lesson5:29 · with Sigrid
Mental model: Think of a function like a private office with its own whiteboard. You can write notes on that board while working inside, but the moment you walk out, the building staff erases it clean. The hallway outside is your global scope: everything written there stays visible to everyone in the building.
Why: You need this separation so a helper function does not accidentally overwrite data used by other parts of your program. If every variable shared one giant space, changing total for a receipt printer would also change the player's score in the game engine.

Local variables

def calculate_tax(price):
    tax = price * 0.1
    print(f"Tax: {tax}")
calculate_tax(50)
print(tax)
The last line raises a NameError because tax does not exist outside the function.
tax was created inside calculate_tax. It is local. Python discards it when the function finishes. You cannot reach it from outside, which keeps the rest of your program tidy and predictable.

Reading globals

high_score = 950
def display_rank():
    print(f"Current high: {high_score}")
display_rank()
A function can read a global variable without any special keyword.
Reading is free. Python checks the local scope first; if it does not find the name there, it falls back to the global scope automatically. You do not need global for read-only access.

Changing globals

level = 1
def advance():
    level += 2
advance()
print(level)
This raises an UnboundLocalError, not a NameError.
Watch out: The moment you assign to a name inside a function (like level += 2, short for level = level + 2), Python treats it as local for the entire body. It never falls back to global. To change a global, add the line global level at the top of the function.

Your turn

0 of 2 solved

Exercise 1

+30 XP
Write a function called double_it that takes one argument, stores the argument times two in a local variable named result, and returns result. Then print what double_it(7) returns. Print nothing else.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+30 XP
A global variable level starts at 1. Write a function called read_level that prints only the number in level. Then write a second function called set_level(new_value) that uses the global line to change level. Call read_level() first, then set_level(5), and finally print level again. Print nothing else.
level = 1


def read_level():
    pass


def set_level(new_value):
    pass

Run your code to check it against the tests.