📌 Introduction
In Python programming, understanding variable scope is essential for writing clean and effective code.
Two of the most common scopes in Python are local and global.
These determine where a variable can be accessed or modified.
🎯 Objective
The objective of this lesson is to:
- Differentiate between local and global variables in Python
- Understand how scope affects variable access and modification
- Write a Python program that demonstrates both scopes clearly
💻 Python Code Example
# Global variable
x = 10
def local_scope_example():
# Local variable
x = 5
print("Inside local_scope_example, x =", x)
def global_scope_example():
global x
x = 20
print("Inside global_scope_example, x =", x)
# Initial value of x
print("Initial value of x:", x)
# Call function with local scope
local_scope_example()
# Value of x remains unchanged globally
print("After local_scope_example, x:", x)
# Call function with global scope
global_scope_example()
# Global x is changed
print("After global_scope_example, x:", x)
📖 Program Explanation
- x = 10 is defined at the top level, making it a global variable.
local_scope_example()
creates a new local variablex = 5
, which exists only inside the function.global_scope_example()
uses theglobal
keyword to modify the global variablex
.- The changes made by
local_scope_example()
do not affect the globalx
. - The
global_scope_example()
function successfully modifies the globalx
to 20.
🚀 How to Run This Program
- Copy the Python code above into a file and save it as
variable_scope.py
. - Open a terminal or command prompt.
- Navigate to the directory where the file is saved.
- Run the program using:
python variable_scope.py
- Observe how the value of
x
changes based on the scope.