26. Python Scope
Python Scope
A variable is only available from inside the region it is created. This is called scope.
Understanding scope is critical because it dictates what variables you have access to at any given line of code, and prevents variables in different parts of your program from accidentally interfering with each other.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.
Function Inside Function
The local variable can be accessed from a function within the function. The inner function has access to the outer function's scope.
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
Naming Variables
If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables. One available in the global scope (outside the function) and one available in the local scope (inside the function).
The global Keyword
If you need to create a global variable, but are stuck in the local scope, you can use the global keyword. The global keyword makes the variable global.
Knowledge Check
Ready to test your understanding of 26. Python Scope?