Variable Scope#
A variable is usually only available in the scope in which it is defined.
For example, consider the following code:
1def scope_test():
2 # this variable has is in the scope of function scope_test()
3 my_value = 10
4 print(my_value)
5
6my_value = 5
7scope_test()
8print(my_value)
This code will print 10 (from inside scope_test) and then 5
(from outside scope_test). This demonstrates that there are two
instances of my_value
. One is scoped inside scope_test and the other is
scoped outside scope_test (the global scope).
Scoping is very useful because it means we do not need to always choose
unique names for variables. I can use the variable name my_value
in
multiple functions and they will not interfere with each other.
See here for a more detailed explanation: