When you write a variable in Python, it does not automatically exist everywhere. Python uses a concept called scope to decide where a name is visible and where it is not. Global scope is the outermost level — variables defined there can be read from almost anywhere in your program.
Every Python name — a variable, a function, a class — lives somewhere. That somewhere is its scope. Understanding scope is one of the first conceptual walls beginners hit, and getting it right saves hours of confusing bugs later. This tutorial starts from scratch and walks through everything a beginner needs to understand global scope with confidence.
What Scope Means in Python
Scope is the region of a program where a name is visible and can be used. Python determines which names are available at any point in the code by following a lookup order called the LEGB rule: Local, Enclosing, Global, Built-in. When Python encounters a name, it searches those four layers in order, stopping at the first match.
L — Local: names defined inside the current function.
E — Enclosing: names in any outer functions that wrap the current one (relevant for nested functions).
G — Global: names defined at the top level of the module.
B — Built-in: names Python provides automatically, such as print, len, and range.
For beginners writing simple scripts, the two levels that matter the most are local and global. The other two become relevant later when writing nested functions or overriding built-ins.
Here is a minimal example that shows scope at work. Python has no trouble finding language inside the function even though it was defined outside it:
language = "Python" # defined at module level — global scope
def greet():
print(language) # Python finds this in global scope
greet() # Output: Python
Python walked the LEGB chain: it looked in greet's local scope, found nothing, then looked in global scope and found language there.
Build a valid assignment that puts the string "Python" into a global variable called language:
= sign. Double == is a comparison operator. The correct form is language = "Python" written at the top level of the file (outside any function) to place it in global scope.
What Global Scope Is
Global scope in Python is the module level. Any assignment written outside all functions and classes creates a name in global scope. That name is then visible to every function defined in the same file, without needing to pass it as an argument.
The diagram below illustrates how global scope wraps local scopes. Functions can see inward from global to local, but the reverse is not true — a local variable cannot be seen from global scope.
Python tracks global scope as a dictionary. You can inspect it at any time by calling the built-in globals() function. It returns every name currently in global scope alongside its value.
score = 100
print("__name__" in globals()) # True
print("score" in globals()) # True
print(globals()["score"]) # 100
The key __name__ is always present because Python puts it there automatically. When you run a file directly, __name__ holds the string "__main__". That is the same value checked in the familiar if __name__ == "__main__": guard.
Global scope in Python is module-level, not truly program-wide. A name defined globally in app.py is not automatically visible in utils.py. To share names across modules you must import them explicitly.
- Global variable
- Any assignment written at the top indentation level of a .py file, outside all functions and classes.
- Local variable
- Any assignment written inside a function body. It only exists while that function is running.
- Global variable
- For the entire lifetime of the program (or until the module is unloaded). It persists between function calls.
- Local variable
- Created when the function is called and destroyed the moment the function returns.
- Global variable
- Any function or class in the same module can read it without any special declaration.
- Local variable
- Only the function that created it. Code outside the function cannot see it at all.
- Global variable
- Only code running at module level, or a function that has declared the name with the
globalkeyword first. - Local variable
- Only the function that owns it. Assigning inside a function without
globalcreates a new local, leaving the global unchanged.
Local Scope vs Global Scope
The single most common mistake beginners make with scope is trying to modify a global variable inside a function without telling Python that is the intention. Python assumes any name you assign inside a function is a new local variable unless told otherwise.
counter = 0 # global variable
def increment():
counter = counter + 1 # WRONG — raises UnboundLocalError
increment()
# UnboundLocalError: local variable 'counter' referenced before assignment
The error surprises beginners because counter clearly exists at the top of the file. What happened? As soon as Python sees an assignment (counter = ...) anywhere in a function, it decides the entire function treats counter as a local variable. Then the right-hand side (counter + 1) tries to read that local variable before it has a value, causing the error.
Reading a global variable inside a function works fine without any declaration. Reassigning it does not — you must use the global keyword first. Many beginners discover this rule only when they hit their first UnboundLocalError.
The fix is one line: declare the name with global at the top of the function body, before any use of that name.
counter = 0
def increment():
global counter # tell Python to use the global binding
counter = counter + 1
increment()
increment()
print(counter) # 2
With global counter in place, Python no longer creates a local variable. Both the read and the assignment now operate on the module-level binding.
Variable Shadowing
A related issue is variable shadowing. If a local variable has the same name as a global one, the local version hides the global one for the entire duration of that function call.
name = "global Kandi"
def show_name():
name = "local Kandi" # shadows the global
print(name) # prints "local Kandi"
show_name()
print(name) # prints "global Kandi" — global unchanged
The global name variable is never touched. Inside show_name, Python created a completely separate local variable that happens to share the same name. Once the function returns, the local disappears. Shadowing is not an error; Python allows it. It is, however, a frequent source of confusing behaviour.
"Names in Python are looked up at the time they are evaluated, not at parse time." — Python Language Reference, Execution Model
The code below tries to increase a global score variable by 10. One line has a bug. Click the line you think is wrong, then hit check.
global score as the first line of add_points(), before the assignment. Without it, Python treats score on line 4 as a local variable that does not exist yet, raising UnboundLocalError.
How to Use Global Variables in Python
Follow these four steps whenever you need a function to both read and reassign a module-level variable.
-
Define a variable at module level
Write the assignment outside all functions, at the leftmost indentation level of your file. This automatically places the name in global scope. Example:
visit_count = 0at the top ofapp.py. -
Read the global variable inside a function
Simply reference the name inside the function body. Python walks the LEGB chain and finds it in global scope automatically. No keyword is needed for read-only access:
def show(): print(visit_count)works without any declaration. -
Declare the global keyword before reassigning
If the function needs to change the variable, write
global visit_countas the very first statement inside the function, before any use of that name. Then assign normally:visit_count += 1. Python now modifies the module-level binding instead of creating a local shadow. -
Verify with globals()
Call
globals()at any point to inspect the current global namespace as a plain dictionary. Check that your variable is present and holds the expected value:print(globals()["visit_count"]).
Here is the full pattern put together cleanly:
# Step 1 — module-level definition
visit_count = 0
# Step 2 — reading without global keyword (fine)
def show_count():
print("Visits so far:", visit_count)
# Step 3 — reassigning with global keyword
def record_visit():
global visit_count
visit_count += 1
record_visit()
record_visit()
show_count() # Visits so far: 2
# Step 4 — verify
print(globals()["visit_count"]) # 2
For larger programs, reaching for the global keyword often signals that a function argument or a return value would be a cleaner design. Reserve global variables for configuration constants and simple counters that are genuinely shared across the whole module.
Python Learning Summary Points
- Global scope is the module level. Any name assigned outside all functions and classes lives there and persists for the lifetime of the program.
- Functions can read global variables without any special keyword. They cannot reassign them without first declaring
global variable_nameinside the function body. - Python resolves names using the LEGB rule: Local first, then Enclosing, then Global, then Built-in. Global scope is the third stop in that chain.
- Assigning inside a function without
globalcreates a brand-new local variable, leaving the global variable untouched and potentially causing anUnboundLocalErrorif the local is read before being assigned. - Variable shadowing happens when a local name matches a global name. The local hides the global for the duration of the function call. It is not an error, but it is a common source of unexpected behaviour.
- Call
globals()to inspect the global namespace at runtime and verify which names are present and what values they hold.
Scope is one of those ideas that clicks quickly once you have seen the error it produces. After encountering your first UnboundLocalError and fixing it with the global keyword, the mental model becomes permanent.
Frequently Asked Questions
Global scope in Python refers to the outermost level of a program. Any variable defined at the top level of a script or module — outside all functions and classes — lives in global scope and can be read from anywhere in that same file.
A variable in local scope exists only inside the function where it was created and is destroyed when the function returns. A variable in global scope exists at the module level and persists for the lifetime of the program, accessible from any function in the same file.
Place the global keyword followed by the variable name at the top of the function body, before any assignment. For example: global counter. This tells Python that any assignment to that name inside the function should modify the global variable rather than create a new local one.
Yes. A function can read (but not reassign) a global variable without declaring it with the global keyword. Python will look up the LEGB chain — Local, Enclosing, Global, Built-in — and find the value at the global level automatically.
Python creates a brand-new local variable with the same name instead of modifying the global one. The global variable is left unchanged. If the right-hand side of the assignment also reads that same name, Python raises an UnboundLocalError because the local has not been assigned a value yet.
LEGB stands for Local, Enclosing, Global, Built-in. It describes the order Python searches for a name when it is referenced. Python checks the local function scope first, then any enclosing function scopes, then the module's global scope, and finally the built-in scope that contains names like print and len.
For small scripts, global variables are fine. In larger programs they make code harder to test, debug, and reason about because any function can silently change them. The preferred approach is to pass values as function arguments and return results explicitly.
Variable shadowing happens when a local variable inside a function has the same name as a global variable. The local name hides the global one within that function, so the global variable cannot be accessed by that name for the duration of the function call.
Call the built-in globals() function. It returns a dictionary of all names and their values currently in the global scope. Similarly, locals() shows the local scope of the current function.
Not exactly. In Python, global scope is module-level, not truly program-wide. A variable declared global in one module is not automatically visible in another module. To share a name across modules you must import it explicitly.