Local and Global Scope in Python
1. Difference Between Local and Global Scope:
Difference Between Local and Global Scope:
| Aspect | Local Scope | Global Scope |
|-------------------|-----------------------------------------------|-----------------------------------------------|
| Definition | The area within a function where local | The area outside all functions, accessible |
| | variables are recognized. | everywhere in the code. |
| Variable Lifespan | Exists only while the function runs. | Exists as long as the program runs. |
| Declared | Inside a function. | Outside all functions. |
| Accessed in | Only inside the function where it's defined. | Anywhere in the program. |
2. Example without using 'global' keyword:
Example 1 - Without global keyword:
x = 10 # Global variable
def my_function():
x = 5 # Local variable
print("Inside function, local x =", x)
my_function()
print("Outside function, global x =", x)
Output:
Inside function, local x = 5
Outside function, global x = 10
3. Example using 'global' keyword:
Example 2 - Using global keyword:
Local and Global Scope in Python
x = 10
def my_function():
global x
x=5
print("Inside function, modified global x =", x)
my_function()
print("Outside function, global x =", x)
Output:
Inside function, modified global x = 5
Outside function, global x = 5