ποΈ What is Scope?
Scope defines where a variable can be accessed and how long it exists in the program.
πΈ Types of Scope:
Local Variable: Declared inside a function and accessible only within that function.
Global Variable: Declared outside of all functions and accessible throughout the file.
π Example:
x = 10 # Global variable
def sample():
x = 5 # Local variable
print("Local x:", x)
sample()
print("Global x:", x)Local x: 5
Global x: 10β Modifying Global Variables
To modify a global variable inside a function, use the global keyword:
x = 10
def modify():
global x
x = 20 # Modifies the global 'x'
modify()
print("Modified Global x:", x)Modified Global x: 20π‘ Why Is Scope Important?
Prevents accidental overwriting of variables
Keeps code modular and easier to debug
Encourages clean and maintainable structure