The scope of a variable refers to where in the program the variable can be accessed, and the scope is determined by where the variable is defined.
For this guide we are going to cover kinds of scope, global and local. Local variables are defined within a function and are accessible only within the function itself. Global variables are defined in the main body of a file and are accessible throughout.
Take the following code snippet as an example:
#!/usr/bin/env python3
result = 55
def print_result():
print(result)
The function print_result
has access to the result
variable because it's defined in the main body of the file. So when we call the function, it will print exactly what we expect. In this case, result
is a global variable.
In the following example, result
is a local variable.
#!/usr/bin/env python3
def get_result():
result = 55
return result
One might be tempted to try and access this variable outside of the function, but it cannot be accessed as it's scoped locally, meaning it's accessible only to the function that defines it.
#!/usr/bin/env python3
def get_result():
result = 55
return result
print(result)
This will result in the following traceback, because result
is not defined in the scope in which it's being accessed.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'result' is not defined
If you found this guide useful, you may want to check out this one on class vs. instance variables in Python 3.