In Python, variables can have different scopes depending on where they are declared.
They are mainly classified as Local or Global based on their visibility and lifetime.
| Feature | Local Variable | Global Variable |
|---|---|---|
| Definition | A variable declared inside a function and accessible only within that function. | A variable declared outside all functions, accessible throughout the program. |
| Scope | Limited to the function where it is defined. | Available to all functions and modules in the program. |
| Lifetime | Created when the function starts, destroyed when the function ends. | Exists for the entire program execution. |
| Declaration | Declared inside a function (no global keyword). | Declared outside any function or explicitly using global. |
| Modification Inside Function | Can be modified only if declared using the global keyword. | Can be modified directly or from inside a function (with global). |
🧩 Example 1: Local Variable
def my_function():
x = 10 # Local variable
print("Inside function:", x)
my_function()
# print(x) # ❌ Error: x is not defined outside functionOutput:
Inside function: 10🧩 Example 2: Global Variable
x = 20 # Global variable
def show():
print("Inside function:", x)
show()
print("Outside function:", x)Output:
Inside function: 20
Outside function: 20🧩 Example 3: Modifying Global Variable Inside a Function
x = 5 # Global variable
def modify():
global x # Declare that we are using global variable
x = 10
print("Inside function:", x)
modify()
print("Outside function:", x)Output:
Inside function: 10
Outside function: 10🧩 Example 4: Local Variable with Same Name as Global
x = 100 # Global variable
def test():
x = 50 # Local variable (different from global)
print("Inside function:", x)
test()
print("Outside function:", x)Output:
Inside function: 50
Outside function: 100🧩 Example 5: Using Both Local and Global Variables
x = 10 # Global variable
def sample():
y = 5 # Local variable
print("Global x:", x)
print("Local y:", y)
sample()Output:
Global x: 10
Local y: 5🔹 In Summary
- Local variables exist only inside functions and are temporary.
- Global variables exist outside functions and are accessible everywhere.
- The
globalkeyword is used to modify a global variable inside a function. - Keeping variable scopes clear helps avoid naming conflicts and bugs.
