Its all about the scope of a variable
variable defined at the top of all functions will have global scope.
variables defined in function are called local variables & the life of that variable is with in the function only .
#### Global variable
a = 10
#### funtion defination
def display():
b=20
print(“the value of a from a display function”,a)
print(“the value of b from a display function”,b)
###### function call
display()
print(“the value of b from main function”,b)
o/p
the value of a from a display function 10
the value of b from a display function 20
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-4-bfab6779e705> in <module>
9 display()
10
---> 11 print("the value of b from a display function",b)
NameError: name 'b' is not defined
Calling local variable that is present in another function will fail
#### Global variable
a = 10
#### funtion defination
def display():
b=20
print(“the value of a from a display function”,a)
print(“the value of b from a display function”,b)
###### function call
display()
def display2():
print(“the value of b in second function”,b)
display2()
o/p:
the value of a from a display function 10
the value of b from a display function 20
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-a8be151a7df3> in <module>
12 print("the value of b in second function",b)
13
---> 14 display2()
<ipython-input-2-a8be151a7df3> in display2()
10
11 def display2():
---> 12 print("the value of b in second function",b)
13
14 display2()
NameError: name 'b' is not defined