Understanding Variable Scope in Python
========================================
Introduction
------------
- Greet audience and introduce yourself.
- Briefly explain what variables are in Python.
- Hook: Ask - 'Have you ever gotten a "variable not defined" error and didn't know
why?'
What is Scope?
--------------
- Definition: The region of a program where a variable is recognized.
- Explain why scope matters — it affects how/where variables can be accessed or
modified.
Types of Variable Scope in Python
---------------------------------
- A. Local Scope
- Defined inside a function.
- Accessible only within that function.
Example:
def my_func():
x = 10
print(x)
- B. Global Scope
- Defined outside all functions.
- Accessible everywhere in the file.
Example:
x = 10
def my_func():
print(x)
- C. Enclosing Scope (Nonlocal)
- Variable in outer function, used in nested function.
Example:
def outer():
x = 'Python'
def inner():
print(x)
inner()
- D. Built-in Scope
- Names preassigned in Python (like len, print, etc.)
The LEGB Rule
-------------
- Order Python searches for variables: Local -> Enclosing -> Global -> Built-in.
- Give a quick example that walks through this hierarchy.
Global and Nonlocal Keywords
----------------------------
- global - Allows modifying a global variable inside a function.
Example:
x = 5
def change():
global x
x = 10
- nonlocal - Used in nested functions to modify a variable in an outer (non-global)
scope.
Example:
def outer():
x = 'Python'
def inner():
nonlocal x
x = 'Java'
Common Errors & Best Practices
------------------------------
- Variable shadowing.
- Avoid excessive use of global.
- Prefer function parameters and return values over global changes.
Conclusion & Q&A
----------------
- Recap: Scope determines variable visibility.
- LEGB rule is key.
- Invite questions.