Variable Scope

Now that you have seen variables and program blocks, both functions and loops, you can study the scope of variables.

External variables can be used inside blocks but not the other way around. Variables internal to a block cannot be used outside the block.

We will see some examples of the scope of variables, that is, where they can be used and where not.

global statement

Global variables are those defined in the body of the program, not within loops or functions.

Example of global variable:

def mensaje():
    print('Número =', numero)

numero = 10
mensaje()
numero = 11
mensaje()

Exit:

Número = 10
Número = 11

In the above case, the global variable 'number' can be read inside the 'message()' function.

However, if we try to update the 'number' variable inside the 'message()' function it won't work because we are creating two variables. One variable will be the global variable 'number' and another will be the local variable 'number', which have the same name, but are different.

Example of global variable and local variable of the same name generating an error:

def mensaje():
    print('Número =', numero) # variable local no definida (error)
    numero = 11               # variable local

numero = 10 # variable global
mensaje()
mensaje()

Exit:

print('Número =', numero)
UnboundLocalError: cannot access local variable 'numero' where it is
not associated with a value

To fix the problem we have to use the global statement that declares 'number' as a global variable, not a local one.

Example of global variable without error:

def mensaje():
    global numero
    print('Número =', numero)
    numero = 11

numero = 10
mensaje()
mensaje()

Exit:

Número = 10
Número = 11