Python Mastery – From Basics to Brilliance / Modules & Packages

Scope: Local vs Global Variables

πŸ—‚οΈ 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