Python
Python Basics
- Introduction to Python and Its History
- Python Syntax and Indentation
- Python Variables and Data Types
- Dynamic and Strong Typing
- Comments and Docstrings
- Taking User Input (input())
- Printing Output (print())
- Python Operators (Arithmetic, Logical, Comparison)
- Type Conversion and Casting
- Escape Characters and Raw Strings
Data Structures in Python
- Lists
- Dictionaries
- Dictionary Comprehensions
- Strings and String Manipulation
- Tuples
- Python Sets: Unordered Collections
- List Comprehensions and Generator Expressions
- Set Comprehensions
- String Formatting
- Indexing and Slicing
Control Flow and Loops
- Conditional Statements: if, elif, and else
- Loops and Iteration
- While Loops
- Nested Loops
- Loop Control Statements
- Iterators and Iterables
- List, Dictionary, and Set Iterations
Functions and Scope
- Defining and Calling Functions (`def`)
- Function Arguments (`*args`, `**kwargs`)
- Default Arguments and Keyword Arguments
- Lambda Functions
- Global and Local Scope
- Function Return Values
- Recursion in Python
Object-Oriented Programming (OOP)
- Object-Oriented Programming
- Classes and Objects
- the `__init__()` Constructor
- Instance Variables and Methods
- Class Variables and `@classmethod`
- Encapsulation and Data Hiding
- Inheritance and Subclasses
- Method Overriding and super()
- Polymorphism
- Magic Methods and Operator Overloading
- Static Methods
- Abstract Classes and Interfaces
Python Programs
- Array : Find median in an integer array
- Array : Find middle element in an integer array
- Array : Find out the duplicate in an array
- Array : Find print all subsets in an integer array
- Program : Array : Finding missing number between from 1 to n
- Array : Gap and Island problem
- Python Program stock max profit
- Reverse words in Python
- Python array duplicate program
- Coin change problem in python
- Python Write fibonacci series program
- Array : find all the pairs whose sum is equal to a given number
- Find smallest and largest number in array
- Iterate collections
- List comprehensions
- Program: Calculate Pi in Python
- String Formatting in Python
Global and Local Scope in Python: Master global
and nonlocal
Python is an easy-to-learn, powerful programming language. However, when working with functions, one concept that confuses many beginners is variable scope—especially how global
and nonlocal
keywords affect variables. Understanding these two concepts is crucial when you’re writing functions that need to interact with variables outside their immediate context.
In this detailed guide, we’ll simplify the idea of scope, clarify when to use global
and nonlocal
, and walk you through easy-to-understand examples so you can master these Python features with confidence.
📌 What Is Variable Scope in Python?
In Python, scope refers to the part of a program where a variable is accessible. Scope defines where you can use or modify a variable in your code. There are mainly four types of scopes in Python, often referred to by the LEGB rule:
- L – Local
- E – Enclosing (nonlocal)
- G – Global
- B – Built-in
This guide will focus on the Local, Global, and Enclosing (nonlocal) scopes.
✅ Why Is Understanding Scope Important?
- 🔁 Helps avoid naming conflicts
- 🛠 Prevents bugs in larger programs
- 💡 Aids in writing modular, clean code
- 📦 Enables better memory management
- 🧠 Essential for working with closures and decorators
🔍 Local Scope in Python
Variables defined inside a function are local to that function.
def greet():
name = "Alice" # local variable
print("Hello", name)
greet()
# Output: Hello Alice
# print(name) # Error: name is not defined outside the function
The variable name
exists only inside the greet()
function. Once the function ends, the variable is destroyed.
🌍 Global Scope in Python
A variable defined outside any function is in the global scope. It can be accessed from any function but not modified unless explicitly declared global.
name = "Bob" # global variable
def greet():
print("Hello", name)
greet()
# Output: Hello Bob
Here, the function greet()
can read the global variable name
, but it cannot change it unless we use the global
keyword.
🔁 Using the global
Keyword
The global
keyword tells Python that a variable declared inside a function should refer to the global version.
✅ Example:
count = 0
def increment():
global count
count += 1
increment()
print(count) # Output: 1
Without global
, Python would think count
is a new local variable and throw an error.
⚠️ Common Mistake Without global
counter = 10
def increase():
counter += 1 # UnboundLocalError
increase()
Even though counter
is global, Python treats it as a new local variable since it’s being modified. To fix it, use global counter
.
🧩 The nonlocal
Keyword in Nested Functions
Python also supports nested functions, where one function is defined inside another. In such cases, you may want the inner function to modify a variable from the outer function’s scope—not global, not local.
This is where nonlocal
comes in.
✅ Example of nonlocal
def outer():
msg = "Hi"
def inner():
nonlocal msg
msg = "Hello"
inner()
print(msg)
outer()
# Output: Hello
Without nonlocal
, the msg
variable inside inner()
would be treated as a new local variable. With nonlocal
, it refers to the msg
in the enclosing function (outer()
).
⚙️ Real-World Use Cases
1. Global Config Settings
config = {"debug": False}
def enable_debug():
global config
config["debug"] = True
2. Simple Counter with Global
counter = 0
def next_value():
global counter
counter += 1
return counter
3. Closures with nonlocal
def make_multiplier(factor):
def multiply(number):
return number * factor
return multiply
double = make_multiplier(2)
print(double(5)) # Output: 10
To make factor
changeable, you’d use nonlocal
inside multiply()
.
🚫 Common Mistakes and Confusion
❌ 1. Modifying Global Variables Without global
x = 5
def update():
x = x + 1 # UnboundLocalError
✅ Fix:
def update():
global x
x = x + 1
❌ 2. Overusing Global Variables
Using global variables excessively leads to messy, hard-to-maintain code. Prefer passing arguments to functions instead.
🧾 Best Practices
- ✅ Use local variables by default
- ✅ Use
global
only when absolutely necessary - ✅ Use
nonlocal
for nested functions to avoid global pollution - ✅ Keep your variable scope as limited as possible
- ✅ Comment where you use
global
ornonlocal
for clarity
📌 Summary
Concept | Scope | Can Read | Can Modify |
---|---|---|---|
Local Variable | Inside function | ✅ | ✅ |
Global Variable | Outside function | ✅ | ✅ (with global ) |
Nonlocal Variable | Enclosing function | ✅ | ✅ (with nonlocal ) |
Understanding global
and nonlocal
is crucial when you’re writing functions that interact with variables outside their local scope. While they offer powerful capabilities, they must be used wisely to keep your code clean, modular, and error-free.
Mastering variable scope helps you avoid subtle bugs and write Python code that scales well. So, next time you encounter scope-related errors, you’ll know exactly how to fix them!