- Python Features
- Python Installation
- PyCharm Configuration
- Python Variables
- Python Data Types
- Python If Else
- Python Loops
- Python Strings
- Python Lists
- Python Tuples
- Python List Vs Tuple
- Python Sets
- Python Dictionary
- Python Functions
- Python Files I/O
- Read Write Excel
- Read Write JSON
- Read Write CSV
- Python OS Module
- Python Exceptions
- Python Datetime
- Python Collection Module
- Python Sys Module
- Python Decorator
- Python Generators
- Python OOPS
- Python Numpy Module
- Python Pandas Module
- Python Sqlite Module
1. Local Scope Example
Variables declared inside a function are local to that function.
def my_function():
x = 10 # local variable
print("Inside function:", x)
my_function()
print("Outside function:", x) # ❌ Error: x is not defined
2. Global Scope Example
Variable declared outside a function can be accessed anywhere.
x = 50 # global variable
def display():
print("Inside function:", x)
display()
print("Outside function:", x)
3. Modifying Global Variable Inside a Function
Use the global keyword to change it.
count = 0
def update():
global count
count = count + 1
print("Inside function:", count)
update()
print("Outside function:", count)
4. Enclosing Scope (Nested Functions)
Inner function can access variable from the outer function.
def outer():
name = "Python" # enclosing variable
def inner():
print("Accessing enclosing variable:", name)
inner()
outer()
5. Modify Enclosing Variable using nonlocal
The nonlocal keyword allows modifying a variable in the outer (enclosing) function.
def outer():
count = 10
def inner():
nonlocal count
count += 5
print("Inside inner:", count)
inner()
print("Inside outer:", count)
outer()