- Python supports 2 types of variables.
- Global variables
- Local variables
Global Variables
- The variables which are declared outside of function are called global variables.
- These variables can be accessed in all functions of that module.
Example
Python
a=10
def f1():
print(a)
def f2():
print(a)
f1()
f2()
Output
PowerShell
10
10
Local Variables
- The variables which are declared inside a function are called local variables.
- Local variables are available only for the function in which we declared it i.e. from outside of function we cannot access.
Example
Python
def f1():
a=10
print(a)
def f2():
print(a)
f1()
f2()
Output
PowerShell
10
NameError: name 'a' is not defined
Global Keyword
- We can use global keyword for the following 2 purposes:
- To declare global variable inside function.
- To make global variable available to the function so that we can perform required modifications.
Example
Python
a=10
def f1():
a=777
print(a)
def f2():
print(a)
f1()
f2()
Output
PowerShell
777
10
Example
Python
a=10
def f1():
global a
a=777
print(a)
def f2():
print(a)
f1()
f2()
Output
PowerShell
777
777
Example
Python
def f1():
a=10
print(a)
def f2():
print(a)
f1()
f2()
Output
PowerShell
NameError: name 'a' is not defined
Example
Python
def f1():
global a
a=10
print(a)
def f2():
print(a)
f1()
f2()
Output
PowerShell
10
10
Note
- If global variable and local variable having the same name then we can access global variable inside a function as follows:
Python
a=10
def f1():
a=777
print(a)
print(globals()['a'])
f1()
Output
PowerShell
777
10
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!