Python Functions Scope

Understanding Variable Scope

In Python, variable scope determines where a variable is accessible within your code. It's essential to understand scope to avoid unexpected errors and to write clean, predictable functions.


What Is Variable Scope?

Scope refers to the region of the code where a variable is recognized.

There are two main types of scope in Python:

  • Global scope: variables defined outside all functions
  • Local scope: variables defined inside a function

Let’s break them down.


Local Scope in Functions

When you create a variable inside a function, it only exists within that function.

def greet():
    message = "Hello!"
    print(message)

greet()

Output:

Hello!

Trying to access message outside the function will raise an error:

print(message)  # This will cause an error

Error:

NameError: name 'message' is not defined

Global Scope

Variables declared outside of functions are in the global scope. You can access them from inside functions, but you cannot modify them unless you explicitly tell Python to do so.

name = "Alice"

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

greet()

Output:

Hello, Alice!

Here, name is a global variable, and the function is reading it, which is allowed.


Trying to Modify a Global Variable Inside a Function

By default, you cannot modify a global variable inside a function. Python creates a new local variable instead.

counter = 0

def increment():
    counter = counter + 1
    print(counter)

increment()

Error:

UnboundLocalError: local variable 'counter' referenced before assignment

Python thinks you're trying to use a local variable counter before it has been assigned, because you're assigning to it inside the function.


Using the global Keyword

To actually modify a global variable from inside a function, use the global keyword.

counter = 0

def increment():
    global counter
    counter = counter + 1
    print(counter)

increment()

Output:

1

Now it works, because you explicitly told Python to use the global counter.


Why Be Careful with global?

Using global too much leads to code that is hard to debug and test. It’s better to return values and update them outside the function when possible.


Best Practice: Return Values

Instead of using global, return the new value from the function.

def increment(counter):
    return counter + 1

count = 0
count = increment(count)
print(count)

Output:

1

This way, you avoid side effects and keep your functions predictable.


Nested Functions and Enclosing Scope

When you define a function inside another, the inner function can access variables from the enclosing function, but not modify them directly unless you use nonlocal.

def outer():
    message = "Hi"

    def inner():
        print(message)

    inner()

outer()

Output:

Hi

Modifying Enclosing Variables with nonlocal

To modify a variable from the enclosing (non-global) scope, use nonlocal.

def outer():
    count = 0

    def inner():
        nonlocal count
        count += 1
        print(count)

    inner()

outer()

Output:

1

This tells Python to use the count variable from the enclosing function scope.


Summary

  • Local variables exist only within the function.
  • Global variables can be read from functions but require global to be modified.
  • Avoid modifying globals unless absolutely necessary.
  • Use function return values for safer, more predictable code.
  • For nested functions, use nonlocal to modify enclosing variables.

Understanding scope will help you write functions that are easier to understand, reuse, and debug.

Continue Learning

Python Variables

Popular

### Understanding Variables and Literals in Python Variables and literals are the foundation of any

Python List

For You

### Python Lists: A Complete Introduction Lists are one of the most versatile and commonly used dat

Python For Loop

For You

### The for Loop in Python The `for` loop is used to execute a block of code multiple times by iter

Personalized Recommendations

Log in to get more relevant recommendations based on your reading history.