
Python
Scope determines where variables can be accessed. Understanding scope helps you write bug-free code.
Scope is the region of code where a variable can be accessed.
Variables created inside a function exist only in that function:
def greet():
message = "Hello!" # Local variable
print(message)
greet() # Works: prints "Hello!"
print(message) # ❌ ERROR! message doesn't exist hereOutput:
Hello!
Traceback (most recent call last):
File "script.py", line 4, in <module>
print(message)
NameError: name 'message' is not definedVariables created outside functions are accessible everywhere:
message = "Hello" # Global variable
def greet():
print(message) # Can access global variable
greet() # Works: prints "Hello"
print(message) # Works: prints "Hello"Output:
Hello
Helloglobal_var = "I'm global" # Global scope
def my_function():
local_var = "I'm local" # Local scope
print(global_var) # ✅ Can access global
print(local_var) # ✅ Can access local
my_function()
# Output:
# I'm global
# I'm local
print(global_var) # ✅ Can access global
print(local_var) # ❌ Error! local_var not accessible here| Variable | Accessible Where | Code |
|---|---|---|
| Local | Only inside its function | `def func(): x = 5` |
| Global | Outside functions, everywhere | `x = 5` (not in function) |
# Global configuration
API_KEY = "secret-123"
DEBUG = True
def fetch_data(url):
# Local variables - only for this function
response = "data from API"
status = 200
# Can use global variables
if DEBUG:
print(f"Using API key: {API_KEY}")
return response
# Can use globals here
print(f"API Key: {API_KEY}")
print(f"Debug mode: {DEBUG}")
# Cannot use locals here (response, status don't exist)
# This would error: print(response)A local variable can have the same name as a global variable:
x = "global" # Global variable
def my_function():
x = "local" # Local variable (shadows global)
print(x) # Prints the local one
my_function() # Output: local
print(x) # Output: globalIf you need to modify a global variable from inside a function, use `global`:
counter = 0 # Global variable
def increment():
global counter # Tell Python: use the global counter
counter += 1
increment()
increment()
print(counter) # Output: 2counter = 0
def increment():
counter += 1 # ❌ Error! counter is local now
increment() # UnboundLocalError!# ❌ Bad - too many globals
global_x = 0
global_y = 0
global_z = 0
def process():
global global_x, global_y, global_z
global_x += 1
# ✅ Better - use return values
def process(x, y, z):
return x + 1, y, z# ✅ Good - local variables
def calculate_area(length, width):
area = length * width
return area
# Function doesn't change anything outside itself# ❌ Bad - relies on global
value = 10
def double():
global value
value *= 2
# ✅ Good - uses parameters
def double(x):
return x * 2
result = double(10)account_balance = 1000 # Global
def deposit(amount):
# Local variables
transaction_fee = 5
new_amount = amount - transaction_fee
global account_balance
account_balance += new_amount
return account_balance
deposit(100)
print(account_balance) # Can access global here# GLOBAL SCOPE
x = 10
def function1():
# LOCAL SCOPE (function1)
y = 20
print(x) # ✅ Can access global x
print(y) # ✅ Can access local y
def function2():
# LOCAL SCOPE (function2)
z = 30
print(x) # ✅ Can access global x
# print(y) # ❌ Can't access y from function1
print(z) # ✅ Can access local z
function1()
function2()
print(x) # ✅ Can access global x
# print(y) # ❌ Can't access local y from function1
# print(z) # ❌ Can't access local z from function2| Concept | Remember |
|---|---|
| Local scope | Variables inside functions |
| Global scope | Variables outside functions |
| Local only | Local variables exist only in their function |
| Global access | Global variables accessible from functions |
| Shadowing | Local variable hides global with same name |
| global keyword | Needed to modify global from function |
| Best practice | Keep globals minimal, use parameters |
You've learned the fundamentals! Now explore default parameters and advanced parameter techniques to create even more powerful and flexible functions.
Practice: Try scope challenges
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward