Python Basics — Day 17 Local vs Global Variables & Scope
Aspiring Full-Stack Developer | Python · Django · React · SQL | documenting my learning journey
Building skills in Python and full-stack development, with a focus on web apps and system design
Junior developer in training — Python, Django, React — preparing for a career in full-stack engineering
From Python basics to full-stack projects, sharing my progress as I grow into a developer
Future full-stack engineer | Learning in public: Python, APIs, Databases, and Web Development
01. Local Variables
Declared inside a function
Exist only while the function is running
def show_number():
x = 10 # Local variable
print("Inside function:", x)
show_number()
# print(x) # Error! (x is not defined outside the function)
02. Global Variables
Declared outside of any function
Can be accessed anywhere in the program
y = 20 # Global variable
def print_global():
print("Inside function:", y)
print_global()
print("Outside function:", y)
03. Modifying a Global Variable with global
count = 0
def increase():
global count # Declare to use the global variable
count += 1
increase()
increase()
print(count) # 2
⚠️ Note: Avoid overusing global, as it can make code harder to manage.
04. Name Conflict Between Local and Global Variables
x = 100
def test():
x = 50 # Local variable (different from global x)
print("Inside function:", x)
test()
print("Outside function:", x)
# Inside function: 50
# Outside function: 100
05. Scope Rules (LEGB Rule)
Python searches for variables in the following order:
L (Local) – Inside the current function
E (Enclosed) – In the enclosing (outer) function
G (Global) – In the global scope
B (Built-in) – In Python’s built-in namespace
x = "global"
def outer():
x = "enclosed"
def inner():
x = "local"
print(x) # local
inner()
print(x) # enclosed
outer()
print(x) # global
06. The nonlocal Keyword
- Used inside nested functions to modify a variable in the enclosing function
def outer():
x = "enclosed"
def inner():
nonlocal x
x = "changed"
print("inner:", x)
inner()
print("outer:", x)
outer()
07. Practice Examples
Example 1: Local vs Global
a = 5
def func():
a = 10
print("Inside function:", a)
func()
print("Outside function:", a)
Example 2: Using global
counter = 0
def add():
global counter
counter += 1
add()
add()
print(counter) # 2
Example 3: Using nonlocal
def outer():
msg = "Hello"
def inner():
nonlocal msg
msg = "Hi"
inner()
print(msg)
outer()