Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Why Functions?Parameters & ArgumentsReturn StatementsScopeDefault ParametersVariable Arguments (*args)Lambda FunctionsDecoratorsFunctional ProgrammingBest Practices
Python/Functions/Scope

🌐 Local vs Global Scope

Scope determines where variables can be accessed. Understanding scope helps you write bug-free code.


🏠 What is Scope?

Scope is the region of code where a variable can be accessed.

  • 🏠 **Local scope** — Inside a function
  • 🌍 **Global scope** — Outside functions (everywhere)

📍 Local Scope

Variables created inside a function exist only in that function:

def greet():
    message = "Hello!"        # Local variable
    print(message)

greet()                       # Works: prints "Hello!"
print(message)                # ❌ ERROR! message doesn't exist here

Output:

Hello!
Traceback (most recent call last):
  File "script.py", line 4, in <module>
    print(message)
NameError: name 'message' is not defined

🌍 Global Scope

Variables created outside functions are accessible everywhere:

message = "Hello"             # Global variable

def greet():
    print(message)            # Can access global variable

greet()                       # Works: prints "Hello"
print(message)                # Works: prints "Hello"

Output:

Hello
Hello

🔄 How Scope Works Together

global_var = "I'm global"     # Global scope

def my_function():
    local_var = "I'm local"   # Local scope
    print(global_var)         # ✅ Can access global
    print(local_var)          # ✅ Can access local

my_function()
# Output:
# I'm global
# I'm local

print(global_var)             # ✅ Can access global
print(local_var)              # ❌ Error! local_var not accessible here

📊 Scope Rules Summary

VariableAccessible WhereCode
LocalOnly inside its function`def func(): x = 5`
GlobalOutside functions, everywhere`x = 5` (not in function)

💡 Real-World Example: Config System

# Global configuration
API_KEY = "secret-123"
DEBUG = True

def fetch_data(url):
    # Local variables - only for this function
    response = "data from API"
    status = 200

    # Can use global variables
    if DEBUG:
        print(f"Using API key: {API_KEY}")

    return response

# Can use globals here
print(f"API Key: {API_KEY}")
print(f"Debug mode: {DEBUG}")

# Cannot use locals here (response, status don't exist)
# This would error: print(response)

⚠️ Variable Shadowing

A local variable can have the same name as a global variable:

x = "global"        # Global variable

def my_function():
    x = "local"     # Local variable (shadows global)
    print(x)        # Prints the local one

my_function()       # Output: local
print(x)            # Output: global

🚀 The global Keyword

If you need to modify a global variable from inside a function, use `global`:

counter = 0         # Global variable

def increment():
    global counter  # Tell Python: use the global counter
    counter += 1

increment()
increment()
print(counter)      # Output: 2

Without global (doesn't work)

counter = 0

def increment():
    counter += 1    # ❌ Error! counter is local now

increment()  # UnboundLocalError!

🎯 Best Practices

1. Minimize Global Variables

# ❌ Bad - too many globals
global_x = 0
global_y = 0
global_z = 0

def process():
    global global_x, global_y, global_z
    global_x += 1

# ✅ Better - use return values
def process(x, y, z):
    return x + 1, y, z

2. Local Variables for Safety

# ✅ Good - local variables
def calculate_area(length, width):
    area = length * width
    return area

# Function doesn't change anything outside itself

3. Pass Data, Not Globals

# ❌ Bad - relies on global
value = 10
def double():
    global value
    value *= 2

# ✅ Good - uses parameters
def double(x):
    return x * 2

result = double(10)

🔍 Scope Example: Bank Account

account_balance = 1000      # Global

def deposit(amount):
    # Local variables
    transaction_fee = 5
    new_amount = amount - transaction_fee

    global account_balance
    account_balance += new_amount

    return account_balance

deposit(100)
print(account_balance)      # Can access global here

📋 Scope Reference

# GLOBAL SCOPE
x = 10

def function1():
    # LOCAL SCOPE (function1)
    y = 20
    print(x)    # ✅ Can access global x
    print(y)    # ✅ Can access local y

def function2():
    # LOCAL SCOPE (function2)
    z = 30
    print(x)    # ✅ Can access global x
    # print(y)  # ❌ Can't access y from function1
    print(z)    # ✅ Can access local z

function1()
function2()

print(x)        # ✅ Can access global x
# print(y)      # ❌ Can't access local y from function1
# print(z)      # ❌ Can't access local z from function2

🔑 Key Takeaways

ConceptRemember
Local scopeVariables inside functions
Global scopeVariables outside functions
Local onlyLocal variables exist only in their function
Global accessGlobal variables accessible from functions
ShadowingLocal variable hides global with same name
global keywordNeeded to modify global from function
Best practiceKeep globals minimal, use parameters

🔗 What's Next?

You've learned the fundamentals! Now explore default parameters and advanced parameter techniques to create even more powerful and flexible functions.

Next: Default Parameters →


Practice: Try scope challenges


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn