Variable scope
Variables are only available in the area where they are defined. This area is called the scope of the variable. Depending on how and where a variable is defined, it may or may not be accessible in certain parts of your code. Here, we will discuss what variables in Python represent, the difference in defining them inside or outside of a function, and how the global
and nonlocal
keywords can be used to override these default behaviors.
Variables
A variable is a mapping between a name and an object at a certain location in the computer’s memory. For example, if you set x = 5
, then x
is the variable’s name, and the value of 5
is stored in memory. Python keeps track of the mapping between the name x
and the location of the value using namespaces. Namespaces can be thought of as dictionaries, with the names as the keys of the dictionary, and locations in memory as the values.
Note that when a variable is assigned to the value of another variable, as...