Unit 3 · Functions
Variable Scope (Local and Global Variables)
Understand where variables live and die in Python.
Learn the difference between local and
global scope, how the global
keyword works, and master the LEGB rule that
governs variable resolution in Python.
Introduction
When you create a variable inside a function, it only exists within that function. When you create a variable outside all functions, it can be accessed from anywhere. This concept is called variable scope.
Understanding scope is critical because it determines where variables can be read and modified. Misunderstanding scope is one of the most common sources of bugs for beginners.
This chapter covers local scope, global scope, the
global keyword, nested functions, the LEGB rule,
and common scope-related errors.
University Definition
Variable scope refers to the region of a program where a variable is accessible. A local variable is defined inside a function and is only accessible within that function. A global variable is defined outside all functions and can be accessed throughout the program.
Local Scope
Variables created inside a function are local to that function. They are created when the function starts and destroyed when it finishes.
def my_function():
x = 10
print("Inside function:", x)
my_function()
print("Outside function:", x) # NameError!
Output: Inside function: 10 NameError: name 'x' is not defined
The variable x only exists inside
my_function(). Trying to access it outside causes
a NameError.
Global Scope
Variables created outside all functions are global and can be accessed from anywhere in the program:
language = "Python" # Global variable
def greet():
print("I love", language)
greet()
print("Outside:", language)
Output: I love Python Outside: Python
The variable language is defined at the module level
and is accessible both inside and outside the function.
Local vs Global Variables
Local Variable
- Created inside a function.
- Only accessible within the function.
- Created when the function is called.
- Destroyed when the function finishes.
- Can have the same name as a global variable without conflict.
Global Variable
- Created outside all functions.
- Accessible throughout the program.
- Created when the program starts.
- Destroyed when the program ends.
- Functions can read but not modify (without
global).
Variable Shadowing
A local variable can have the same name as a global variable. Inside the function, the local version "shadows" (hides) the global one:
x = 100 # Global
def show():
x = 50 # Local — shadows the global x
print("Inside:", x)
show()
print("Outside:", x)
Output: Inside: 50 Outside: 100
The local x = 50 does not affect the global
x = 100. They are two completely separate variables.
The global Keyword
If you need to modify a global variable inside
a function, you must use the global keyword:
count = 0 # Global variable
def increment():
global count
count += 1
print("Count:", count)
increment()
increment()
increment()
print("Final count:", count)
Output: Count: 1 Count: 2 Count: 3 Final count: 3
Warning: Overuse of global
makes code harder to debug. Prefer passing values as
function arguments and returning results instead.
The LEGB Rule
Python follows the LEGB rule to resolve variable names. It checks these scopes in order:
print, len, range).
x = "global" # Global scope
def outer():
x = "enclosing" # Enclosing scope
def inner():
x = "local" # Local scope
print("Inner:", x)
inner()
print("Outer:", x)
outer()
print("Global:", x)
Output: Inner: local Outer: enclosing Global: global
Nested Function and Enclosing Scope
def outer_func():
msg = "Hello from outer"
def inner_func():
print(msg) # Accesses enclosing variable
inner_func()
outer_func()
Output: Hello from outer
The inner function can read variables from the enclosing function. This is the basis of closures in Python.
Real-Life Analogy
Think of a house. The living room (global
scope) is visible to everyone. Each bedroom (local scope) is
private to whoever is inside it. You can have a TV in the
living room and another TV in your bedroom—same name, different
rooms, completely independent. If you want to change the
living room TV from inside your bedroom, you need to explicitly
walk out (the global keyword).
Key Points
Local variables exist only inside their function.
Global variables are accessible throughout the program.
Use global keyword to modify global variables inside a function.
Python resolves names using the LEGB rule.
Local variables shadow global variables of the same name.
Prefer passing values as arguments instead of using global variables.
Common Scope Errors
UnboundLocalError
x = 10
def func():
print(x) # UnboundLocalError!
x = 20
func()
Python sees x = 20 later in the function and
treats x as local. But print(x)
is called before the local x is assigned.
Accessing Local Variable Outside
def func():
x = 10
func()
print(x) # NameError: name 'x' is not defined
University Exam Tip
University exams love asking: "Explain local and global
variables with examples." and "What is the LEGB
rule?" Always provide a clear example showing variable
shadowing and explain that the global keyword
is needed to modify global variables inside a function.
Practice Questions
Q1. What is the difference between a local and a global variable?
Answer: A local variable is defined inside a function and only accessible within it. A global variable is defined outside all functions and accessible throughout the program.
Q2. What does LEGB stand for?
Answer: Local, Enclosing, Global, Built-in. It is the order Python follows to resolve variable names.
Q3. What will be the output?
x = 5
def func():
x = 10
print(x)
func()
print(x)
Output: 10, 5
Q4. Write a function that uses the global keyword to increment a counter.
counter = 0
def increment():
global counter
counter += 1
increment()
increment()
increment()
print(counter) # 3
Q5. Why should you avoid using global variables excessively?
Answer: Global variables can be modified from anywhere, making it hard to track changes and debug programs. It is better to use function parameters and return values.
Summary
- Local variables exist only inside their function.
- Global variables are accessible throughout the program.
- Use the
globalkeyword to modify global variables inside functions. - The LEGB rule determines the order of variable name resolution.
- Local variables shadow global variables of the same name.
- Prefer using parameters and return values over global variables.