Tuesday, 24 January 2017

GLOBAL AND LOCAL VARIABLES IN PYTHON

Global Variables – The variables which are declared outside of the function are called as global variable. Global variables of one module can be used throughout the module.

Example –
a=100
def f1():
    print a
def f2():
    print a
f1()
f2()

Output –
100
100


Local Variables – The variables which are declared within a function are known as local variables. Local variables of one function cannot be accessed outside of that function.

Example –
def f1():
    a=100
    print adef f2():
    print a
    a=200f1()
f2()

Output –
100
Traceback (most recent call last):
  File "C:/Users/om/PycharmProjects/Pythonn/if3.py", line 8, in <module>
    f2()
  File "C:/Users/om/PycharmProjects/Pythonn/if3.py", line 5, in f2
    print a
UnboundLocalError: local variable 'a' referenced before assignment

No comments:

Post a Comment