A variable declared inside the function is called a local variable in Python. Local variables are accessible only inside the function.
Example local variable in Python
Simple example code creates a local variable inside a function and tries to access it outside those functions.
def foo(): local_var = "local" foo() print(local_var)
Output: shows an error (NameError) because we are trying to access a local variable
Example access local variable within a function
def foo(): local_var = "local" print(local_var) foo()
How to use Global and Local variables in the same code
g = "Global " def foo(): global g l = "Local" g = g * 2 print(g) print(l) foo()
Do comment if you have any doubts and suggestions on this Python variable topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.