Python
Global vs Local Variables in Python, Scope Explained with Examples
Understand global and local variables in Python with examples. LEGB rule, global keyword, nested functions explained for CBSE Class 11 and 12 exams.
Variable scope is one of the most confusing topics for CBSE Computer Science students, and one of the most frequently tested in board exams. This guide explains everything you need to know about local variables, global variables, the global keyword, nested functions, and the LEGB rule.
What is Scope?
Scope is the region of a program where a variable is accessible. A variable created inside a function has a different scope than one created outside it.
x = 10 # This variable has global scope
def greet():
y = 20 # This variable has local scope
print(x) # Can access global variable
print(y) # Can access local variable
greet()
print(x) # Works, x is global
# print(y) # ERROR, y is local to greet()
10
20
10
Local Variables
A local variable is created inside a function and can only be used within that function. Once the function finishes, the variable is destroyed.
def calculate():
result = 5 + 3 # local variable
print(result)
calculate()
# print(result) # ERROR: result is not defined
8
Key point: Each function call creates a fresh set of local variables. They do not persist between calls.
def counter():
count = 0
count += 1
print(count)
counter()
counter()
counter()
1
1
1
Every time counter() is called, count starts at 0 again. It does not remember the previous value.
Global Variables
A global variable is created outside all functions, at the top level of the program. It can be read from inside any function.
school = "DPS Delhi"
def show_school():
print(school) # Reading global variable, works fine
show_school()
print(school)
DPS Delhi
DPS Delhi
However, you cannot modify a global variable inside a function without the global keyword.
marks = 90
def update_marks():
marks = 95 # This creates a NEW local variable, does NOT change global
print("Inside:", marks)
update_marks()
print("Outside:", marks)
Inside: 95
Outside: 90
The marks inside the function is a completely separate local variable. The global marks remains 90. This is a very common exam question.
The global Keyword
To modify a global variable inside a function, you must declare it using the global keyword.
marks = 90
def update_marks():
global marks # Now referring to the global variable
marks = 95
print("Inside:", marks)
update_marks()
print("Outside:", marks)
Inside: 95
Outside: 95
Now the global variable is actually changed.
Rules for the global keyword:
- Write
global variable_namebefore using the variable in the function - Do not assign a value on the same line as the
globaldeclaration - The variable must already exist globally, or it will be created globally when assigned
def create_new():
global city
city = "Mumbai" # Creates a global variable
create_new()
print(city) # Works, city is now global
Mumbai
Nested Functions and Enclosing Scope
When a function is defined inside another function, the inner function can access variables from the outer (enclosing) function.
def outer():
message = "Hello from outer"
def inner():
print(message) # Accesses enclosing scope
inner()
outer()
Hello from outer
To modify a variable from the enclosing scope, use the nonlocal keyword (similar to global, but for enclosing functions).
def outer():
count = 0
def inner():
nonlocal count
count += 1
print("Inner count:", count)
inner()
inner()
print("Outer count:", count)
outer()
Inner count: 1
Inner count: 2
Outer count: 2
The LEGB Rule
Python resolves variable names using the LEGB rule. When you use a variable, Python searches in this order:
| Letter | Scope | Meaning |
|---|---|---|
| L | Local | Variables inside the current function |
| E | Enclosing | Variables in the enclosing (outer) function |
| G | Global | Variables at the top level of the module |
| B | Built-in | Names pre-defined in Python (like print, len, range) |
Python checks each scope in order. The first match is used.
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # Finds "local" first (L)
inner()
print(x) # Finds "enclosing" (E for inner, but L for outer)
outer()
print(x) # Finds "global" (G)
local
enclosing
global
What happens if we remove the local assignment?
x = "global"
def outer():
x = "enclosing"
def inner():
# No local x, Python moves to Enclosing scope
print(x)
inner()
outer()
enclosing
What if we remove the enclosing assignment too?
x = "global"
def outer():
def inner():
# No local x, no enclosing x, Python moves to Global scope
print(x)
inner()
outer()
global
Built-in Scope Example
Built-in scope contains Python's pre-defined functions like print, len, int, str, etc.
# Do NOT do this, it shadows the built-in
len = 5
# print(len("hello")) # ERROR: 'int' object is not callable
# To fix, delete the variable
del len
print(len("hello")) # Works again, uses built-in len
5
Exam tip: Never name your variables list, str, int, len, print, input, or type. These shadow the built-in functions and cause errors.
Common Exam Questions with Answers
Q1: What will be the output? (2 marks)
x = 5
def func():
x = 10
print(x)
func()
print(x)
Answer:
10
5
The x = 10 inside func() creates a local variable. The global x remains 5.
Q2: What will be the output? (3 marks)
a = 1
def outer():
a = 2
def inner():
a = 3
print("Inner:", a)
inner()
print("Outer:", a)
outer()
print("Global:", a)
Answer:
Inner: 3
Outer: 2
Global: 1
Each function has its own local a. None of them modify the others because global and nonlocal are not used.
Q3: What will be the output? (3 marks)
count = 0
def increment():
global count
count += 1
increment()
increment()
increment()
print(count)
Answer:
3
The global keyword allows the function to modify the global variable count. Each call adds 1.
Q4: Will this code produce an error? Why? (2 marks)
def test():
print(value)
value = 10
test()
Answer: Yes, this will produce an UnboundLocalError. Because value is assigned inside the function (on the second line), Python treats it as a local variable for the entire function. When print(value) executes on the first line, the local variable has not been assigned yet, so Python raises an error.
Q5: Explain the LEGB rule with an example. (5 marks)
Answer: The LEGB rule defines the order in which Python searches for a variable name:
- L (Local): The current function's scope
- E (Enclosing): The scope of any enclosing function
- G (Global): The module-level scope
- B (Built-in): Python's pre-defined names
x = "global" # Global scope
def outer():
x = "enclosing" # Enclosing scope
def inner():
x = "local" # Local scope
print(x) # Prints "local" (found in L)
inner()
outer()
Python first checks the local scope. If x is not found locally, it checks the enclosing scope, then the global scope, and finally the built-in scope. The first match is used.
Summary Table
| Concept | Meaning |
|---|---|
| Local variable | Created inside a function, accessible only within it |
| Global variable | Created outside all functions, readable everywhere |
global keyword |
Allows a function to modify a global variable |
nonlocal keyword |
Allows an inner function to modify a variable in the enclosing function |
| LEGB rule | Search order: Local, Enclosing, Global, Built-in |
| Shadowing | A local variable with the same name hides the global one |
Master these concepts and you will handle any scope-related question in your CBSE board exam with confidence.
Want to learn more?
Explore free chapter-wise notes with quizzes and code playground
Prefer watching over reading?
Subscribe for free.