Scope
Scope
Variables do not always work everywhere in a program.
Some variables only work inside a function.
Some variables can be used in many places.
This idea is called scope.
What Is Scope?
Scope means where a variable can be used.
Think of scope as the area where a variable is visible and available.
Two Main Types of Scope
- Local scope
- Global scope
Local Scope
A local variable is created inside a function.
It can only be used inside that function.
def greet():
name = "Sara"
print(name)
greet()
Output
Sara
The variable name works inside the function.
Outside the Function
def greet():
name = "Sara"
greet()
print(name)
This gives an error because name only exists inside the function.
Global Scope
A global variable is created outside a function.
It can be used in many places.
city = "Toronto"
def show_city():
print(city)
show_city()
print(city)
Output
Toronto
Toronto
The variable city is outside the function, so it is global.
Local and Global Together
If a local variable has the same name, Python uses the local one inside the function.
name = "John"
def show_name():
name = "Maya"
print(name)
show_name()
print(name)
Output
Maya
John
Why Scope Matters
Scope helps avoid confusion.
It keeps variables organized and prevents accidental changes.
Code Along
country = "Canada"
def show_country():
print(country)
show_country()
Output
Canada
Mini Challenge
Build a scope checker.
Steps:
- Create a global variable called
colorwith valueBlue - Create a function that prints
color - Call the function
- Print
coloragain outside the function
Expected output:
Blue
Blue
Real World Use Case
Programs use scope to manage data in functions, apps, games, and large systems with many variables.
Quiz
- What does scope mean?
- Where does a local variable work?
- Where is a global variable created?
- Which variable is used first inside a function if names match?
Assignment
Create a global variable called language. Print it inside a function and outside the function.
Summary
You learned that scope controls where variables can be used, and the difference between local and global variables.