Local and Global Variables

tags: #python/documentation/python_functions

Understand the Scope of Variables

The scope of the variables refers to where variables can be referenced. A variable created within a function is referred to as a local variable, whereas a variable created outside of a function is referred to as a global variable and are accessible by all parts of the code.

Summary Table

Local Variables Non-Local Variables Global
Definition Variables declared within a function Used in nested functions. Need to be explicitly declared nonlocal to be access references from an outer function. Variables declared outside of a function, or explicitly declared as global within a function.
Scope Can only accessed from within a function. Cannot be referenced from outside the function. Accessible and modifiable by nested functions. Accessible and modifiable from any part of the code (inside and outside of a function).
Lifetime Only exists while the function is being executed. When the function terminates (returns a value), the local variables are destroyed. Same as local variables.
Powered by Forestry.md