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

🌐 Scope — Where Variables Live

Scope is about where a variable can be used. Some variables only work inside functions, others work everywhere.


🏠 Local vs Global

Variables live in different "scopes" depending on where they're created. Local scope means the variable only exists inside a function. Global scope means the variable exists everywhere in your program and can be used both inside and outside functions. Understanding scope helps you avoid errors and use variables correctly.

# Global — works everywhere
name = "Alice"

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

greet()  # Output: Hello Alice
print(name)  # Output: Alice (works here too)

💡 Local Variables Only Work Inside Functions

When you create a variable inside a function, it's a local variable that only exists within that function. Once the function finishes running, that variable disappears and you can't access it anymore. This is actually a good thing because it keeps your code organized and prevents accidents.

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

make_greeting()  # Output: Hello!
print(message)   # ERROR! message only exists inside the function

📝 Global Variables Work Everywhere

When you create a variable outside any function, it becomes a global variable that your functions can read and use. This is useful for storing settings or data that multiple functions need access to. You can use global variables inside functions just by referencing them by name.

count = 0  # Global variable

def increase():
    print(count)  # Can access global

increase()  # Output: 0
print(count)  # Output: 0 (works here too)

🎨 Real-World Example

# Global - settings
DEBUG_MODE = True

def fetch_data():
    # Local - only used here
    response = "data from server"

    # Can use global
    if DEBUG_MODE:
        print(f"Debug: {response}")

    return response

# Global works here
print(f"Debug mode: {DEBUG_MODE}")

# Local doesn't work here
# print(response)  # ERROR!

⚠️ Variable Shadowing

Sometimes you might create a local variable with the same name as a global variable. This is called "shadowing" — the local variable hides or "shadows" the global one. When you use that variable name inside the function, Python uses the local version, not the global one. It's important to be aware of this so you don't accidentally hide global variables you meant to use.

x = "global"

def show():
    x = "local"  # Creates a local x
    print(x)     # Prints local x

show()      # Output: local
print(x)    # Output: global (unchanged)

Inside the function, `x = "local"` creates a NEW local variable. It doesn't change the global one.


✅ Scope Rules

1. Local variables only work inside their function

2. Global variables work everywhere

3. Functions can READ global variables

4. Local variables hide globals with the same name


🔑 Key Takeaways

ConceptRemember
Local scopeVariables inside functions
Global scopeVariables outside functions
Local onlyLocal vars exist only in their function
Access globalFunctions can read global variables
ShadowingLocal variable hides global with same name

🔗 What's Next?

Now let's learn about default parameters — how to make function arguments optional with sensible defaults!

Next: Default Parameters →


Ready to practice? Try challenges or view solutions


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