Concept Explanation
Imagine you are a member of a club. Inside the club's building, they have special rules and items (like a "Members Only" lounge) that don't exist in the outside world.
In Python, Scope refers to the region of a program where a variable is "visible" and can be accessed. If you create a variable inside a function, it belongs to that function's "Local Scope" and vanishes the moment the function finishes. If you create a variable in the main body of your script, it is in the "Global Scope" and can be seen by everything in that file.
Syntax or Core Structure
The LEGB Rule
Python searches for variables in this specific order:
- Local: Inside the current function.
- Enclosing: Inside any parent functions (for nested logic).
- Global: At the top level of the script.
- Built-in: Pre-defined Python terms (like
lenorprint).
# Global Scope
x = "I am global"
def my_func():
# Local Scope
y = "I am local"
print(y)
print(x) # Accessing global from local works!
my_func()
# print(y) # This would CRASH because y doesn't exist out here.
Code Example #1 (Basic)
Using the global keyword. Usually, you can only read a global variable from inside a function. If you want to change it, you must use the global keyword.
score = 0
def update_score():
global score # Tell Python to use the variable from the outside
score += 10
update_score()
print(f"Current Score: {score}")
Code Example #2 (Intermediate)
The Enclosing Scope (Non-local). This happens when you have a function inside another function.
def outer_func():
msg = "Hello from Outer"
def inner_func():
nonlocal msg # Targets the variable in outer_func
msg = "Updated by Inner"
print(f"Inside: {msg}")
inner_func()
print(f"Outside: {msg}")
outer_func()
Real World Example
Imagine you are building a website settings module. You have "Global Settings" (like the Site Name) and "Page Settings" (like a specific page title).
# 📂 Site Configuration
SITE_NAME = "CodeAcademix" # Global
def render_page(title):
page_title = title # Local
print(f"Rendering {page_title} on {SITE_NAME}...")
render_page("Python Basics")
render_page("Advanced Decorators")
Common Mistakes
- UnboundLocalError: This happens when you try to change a global variable inside a function before you've declared
global. Python gets confused about whether you want a new local one or the old global one. - Global Overload: Beginners often use
globalfor everything. This is a bad practice! It makes your code hard to debug because any part of your program could be changing your data. Use function parameters andreturnvalues instead.
Best Practices
- Global Constants: It is okay to use global variables for "Constants"—values that never change. By convention, these are written in ALL_CAPS.
- Keep it Local: Whenever possible, keep your variables inside functions. It keeps your memory clean and prevents different parts of your program from messing with each other’s data.
Practice Exercises
- The Secret Variable: Define a variable
secret = 123at the top of your script. Write a function that tries to printsecret. Then write a second function that defines its ownsecret = 456and prints it. Observe which one uses which value. - The Counter: Write a function that increments a global variable called
countevery time it is called. - Nested Greeting: Create a function
parent()with a variablename = "Parent". Inside it, definechild()which changesnameusingnonlocal.