Table of Contents

Scope of Variables in Python (Local and Global)

Table of Contents

In Python, the scope of a variable determines where in your code the variable can be accessed and modified. Variables can have either a local or global scope, depending on where they are defined.

When a variable is defined inside a function, it has a local scope and can only be accessed within that function. Here’s an example:

def add_numbers(x, y):
    result = x + y
    return result

print(add_numbers(3, 4))    # Output: 7
print(result)    # NameError: name 'result' is not defined

In this example, the result variable is defined inside the add_numbers() function and has a local scope. When the add_numbers() function is called with arguments 3 and 4, the result variable is created and assigned the value 7. However, when we try to print out the value of result outside of the function, we get a NameError because result is not defined in the global scope.

Global variables, on the other hand, can be accessed and modified from anywhere in your code. Here’s an example:

total = 0

def add_number(number):
    global total
    total += number

print(total)    # Output: 7

In this example, we define a global variable called total and a function called add_number() that takes a number as an argument and adds it to the global total variable. We then call the add_number() function twice with arguments 3 and 4, which modifies the value of the global total variable to 7. Finally, we print out the value of total, which is 7.

It’s important to be careful when using global variables, as they can make your code harder to reason about and lead to unexpected behavior. Whenever possible, it’s generally better to use local variables within functions to keep your code modular and easy to understand.


Copyright 2023-24 © Open Code