Variable Scope#
Local Variables#
The variables within the function are called as “local variables”, and are temporarily created during the function execution. These local variables are not available outside the function, and are only accessible within the function’s scope.
def my_function():
x = 10 # Local variable
print(x)
my_function() # Output: 10
print(x) # Error: NameError: name 'x' is not defined
10
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_28524\3681644610.py in <module>
4
5 my_function() # Output: 10
----> 6 print(x) # Error: NameError: name 'x' is not defined
NameError: name 'x' is not defined
Global Variables#
Global variables are defined outside of functions or classes, and are accessible any part of your program. Note that local and global variables can have same name, the function will use the local variable and it will not modify the global variable.
x = 5 # Global variable
def my_function():
x = 10 # Local variable (shadows the global variable)
print(x)
my_function() # Output: 10
print(x) # Output: 5 (global variable value remains unaffected)