Course contentsShow
← Python
Lesson 144 of 1,0603. Functions and ModularizationFree lesson

Understanding Local and Global Scope

You will learn how variable visibility is restricted within function bodies and how to manage data access across different scope levels.

In this lesson, you will learn how Python controls where your variables "live" and how their visibility changes once you start using functions.

The Two Worlds of Variables

When you write code at the very top level of your script, you are working in the Global Scope. Any variable you define here can be accessed by almost any part of your program.

However, once you enter a function, you step into a Local Scope. Think of a function as a private room: anything you define inside that room (the parameters or variables created within the function body) exists only while the function is running. Once the function finishes, those local variables are cleaned up and become invisible to the rest of your program.

Seeing it in Action

Take a look at this example:

player_score = 10  # This is Global

def add_bonus():
    bonus = 5      # This is Local to add_bonus
    total = player_score + bonus
    return total

print(add_bonus())
# print(bonus)   # This would cause a NameError!

In the code above, player_score is defined globally, so the add_bonus function can "look out" and see it. But bonus is defined inside the function. If you try to print(bonus) outside of the function, Python will raise a NameError because that variable does not exist in the global scope; it was trapped inside the function's private room.

Why does this matter?

Scope acts as a safety barrier. By keeping most variables local, you prevent different parts of your program from accidentally overwriting each other’s data. If every variable were global, a variable named count used in one function might be changed by another function without you realizing it, leading to confusing bugs.

Local variables allow you to build "modular" functions—self-contained tools that do one specific job without worrying about the rest of your code's data.

Key Takeaway: Variables defined inside a function are local to that function and cannot be accessed from the outside, while variables defined at the top level are global and accessible throughout your script.