Language: EN

python-ambito-de-variables

Variable Scope in Python

The scope of a variable refers to the part of the program where that variable is accessible. In Python, there are two main types of variable scope: local and global.

  • Local variables: These are defined within a function. Their scope is limited to that function and are not accessible outside of it.
  • Global variables: These are defined outside of any function or in a global scope. They can be accessible from anywhere in the program (both inside and outside of functions).

Local variables

Variables defined within a function have a local scope. This means they are only accessible within that function. If we try to access a local variable from outside the function, Python will generate an error.

def my_function():
    local_variable = "Hello World"
    print(local_variable)

my_function()
# print(local_variable)  # This would generate an error

In this example, local_variable is defined within the function my_function and is only accessible within that function.

Global variables

Variables defined outside of any function have a global scope. This means they are accessible from anywhere in the program (including inside functions).

global_variable = "I am global"

def print_global():
    print(global_variable)

print_global()  # Result: I am global
print(global_variable)  # It is also accessible outside the function

In this case, global_variable is defined outside of the function print_global, so it is a global variable and can be accessed from anywhere in the program.

Using the global keyword

In some cases, we may need to modify a global variable from within a function. To do this, we need to use the global keyword.

global_variable = "I am global"

def modify_global():
    global global_variable
    global_variable = "Modified inside the function"
    print(global_variable)

modify_global()  # Result: Modified inside the function
print(global_variable)  # Now the global variable has been modified

By using global global_variable inside the function modify_global, we are telling Python that we want to modify the global variable global_variable.

Variable scope in nested functions

If we define a function inside another function, the inner function can access the local variables of the outer function, but it cannot modify them directly.

However, if we use the nonlocal keyword, we can modify variables from the outer function.

def outer_function():
    outer_variable = "I am from the outer function"

    def inner_function():
        nonlocal outer_variable
        outer_variable = "Modified by the inner function"
        print("From inner function:", outer_variable)

    inner_function()
    print("From outer function:", outer_variable)

outer_function()

In this example, inner_function can access and modify the variable outer_variable from outer_function due to the use of nonlocal.