Legends ofPythos
Claim your name
Writing Real Programs

Scope: where variables live

Lesson 6 of 16

Watch the lesson1:02 · 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:.2f}")
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 your global namespace clean 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), Python treats it as local for the entire body. It never falls back to global. To modify a true 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 it in a local variable named result, multiplies by two, and returns the product. Then call it with 7 and print the result.
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 the current value of level. Then write a second function called set_level(new_value) that uses the global keyword to reassign level, and call it with 5. Finally print level again.
level = 1


def read_level():
    pass


def set_level(new_value):
    pass

Run your code to check it against the tests.