#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
5 min read

Variable Scope and Namespaces

Learn where variables can be used and how Python finds them

What You'll Learn

  • What scope means
  • Local vs global variables
  • Using global keyword
  • Best practices

What is Scope?

Scope is where a variable can be used. Think of it as the variable's "zone of influence".

Two types:

  1. Local - Inside a function only
  2. Global - Everywhere in the file

Local Variables

Created inside a function, only work inside:

code.py
def greet():
    message = "Hello"  # Local variable
    print(message)

greet()  # Works: Hello
print(message)  # Error! message doesn't exist here

Example:

code.py
def calculate():
    result = 10 + 5  # Local to this function
    return result

print(calculate())  # 15
print(result)  # Error! result only exists in function

Global Variables

Created outside functions, work everywhere:

code.py
name = "John"  # Global variable

def greet():
    print(f"Hello {name}")  # Can read global

greet()  # Hello John
print(name)  # John

Reading vs Changing

Can read global variables:

code.py
count = 0  # Global

def show_count():
    print(count)  # Reading is OK

show_count()  # 0

Cannot change without global:

code.py
count = 0  # Global

def increment():
    count = count + 1  # Error! Can't change global

increment()  # UnboundLocalError

Using global Keyword

Tell Python you want to change a global variable:

code.py
count = 0  # Global

def increment():
    global count  # Now we can change it
    count = count + 1

increment()
print(count)  # 1

increment()
print(count)  # 2

Example: Game score

code.py
score = 0

def add_points(points):
    global score
    score += points
    print(f"Score: {score}")

add_points(10)  # Score: 10
add_points(5)   # Score: 15
add_points(20)  # Score: 35

Local Shadows Global

Local variable hides global with same name:

code.py
x = 10  # Global

def test():
    x = 5  # Local (different from global)
    print(x)

test()   # 5 (local)
print(x) # 10 (global unchanged)

Practice Examples

Example 1: Counter

code.py
counter = 0

def count_call():
    global counter
    counter += 1
    print(f"Function called {counter} times")

count_call()  # Function called 1 times
count_call()  # Function called 2 times
count_call()  # Function called 3 times

Example 2: Settings

code.py
debug_mode = False

def toggle_debug():
    global debug_mode
    debug_mode = not debug_mode
    status = "ON" if debug_mode else "OFF"
    print(f"Debug mode: {status}")

toggle_debug()  # Debug mode: ON
toggle_debug()  # Debug mode: OFF

Example 3: Bank account

code.py
balance = 1000

def deposit(amount):
    global balance
    balance += amount
    print("Deposited $" + str(amount) + ". Balance: $" + str(balance))

def withdraw(amount):
    global balance
    if amount <= balance:
        balance -= amount
        print("Withdrew $" + str(amount) + ". Balance: $" + str(balance))
    else:
        print("Insufficient funds!")

deposit(500)   # Deposited $500. Balance: $1500
withdraw(200)  # Withdrew $200. Balance: $1300

Best Practices

1. Avoid global when possible:

code.py
# Not good
total = 0

def add(x):
    global total
    total += x

# Better - use parameters and return
def add(total, x):
    return total + x

result = add(0, 5)

2. Pass parameters instead:

code.py
# Not good
name = "John"

def greet():
    global name
    print(f"Hello {name}")

# Better
def greet(name):
    print(f"Hello {name}")

greet("John")

3. Return values instead:

code.py
# Not good
result = 0

def calculate(x, y):
    global result
    result = x + y

# Better
def calculate(x, y):
    return x + y

result = calculate(5, 3)

Nested Functions

Functions inside functions:

code.py
def outer():
    x = 10  # Outer function variable

    def inner():
        print(x)  # Can read outer variable

    inner()

outer()  # 10

Using nonlocal:

code.py
def outer():
    x = 10

    def inner():
        nonlocal x  # Change outer function variable
        x = 20

    inner()
    print(x)

outer()  # 20

Common Mistakes

Mistake 1: Forgetting global

code.py
count = 0

def increment():
    count += 1  # Error! Need global

# Correct
def increment():
    global count
    count += 1

Mistake 2: Overusing global

code.py
# Bad - too many globals
total = 0
count = 0
average = 0

# Better - use function parameters
def calculate_stats(numbers):
    total = sum(numbers)
    count = len(numbers)
    average = total / count
    return total, count, average

Mistake 3: Shadowing unintentionally

code.py
name = "Global"

def test():
    name = "Local"  # Created new local, didn't change global
    print(name)

test()       # Local
print(name)  # Global (unchanged)

When to Use Global

Good uses:

  • Configuration settings
  • Application state
  • Constants (values that don't change)
code.py
# Constants (uppercase names)
MAX_USERS = 100
DEBUG = True
API_KEY = "abc123"

def check_users(count):
    if count > MAX_USERS:
        print("Too many users!")

Avoid for:

  • Passing data between functions (use parameters)
  • Temporary calculations (use local variables)
  • Return values (use return statement)

Quick Reference

Read global:

code.py
x = 10

def func():
    print(x)  # Just read, no keyword needed

Change global:

code.py
x = 10

def func():
    global x
    x = 20

Local variable:

code.py
def func():
    x = 10  # Only exists in function

Nested function:

code.py
def outer():
    x = 10

    def inner():
        nonlocal x
        x = 20

Summary

  • Local variables live inside functions
  • Global variables live outside functions
  • Use global keyword to change globals
  • Prefer parameters and return values
  • Avoid global variables when possible
  • Use constants (CAPS_NAMES) for settings

Congratulations!

You've completed the Python basics! You now know:

  • Variables and data types
  • Operators and conditions
  • Loops and functions
  • Scope and namespaces

You're ready to build real Python projects!

SkillsetMaster - AI, Web Development & Data Analytics Courses