Wednesday, 27 November 2019

Global variables and Local variables



def f1():
    a=10
    print(a)
def f2():
    print(a)
"""output:
>>> f1()
10
>>> f2()#error

Def f1():
  a=10
  a+=1
  print(a)
f1()
print(a)#error not available

"""
To avoid this problem we use global variable
 a=10
def f1():
    print(a)
def f2():
    print(a)
"""output:
>>> f1()
10
>>> f2()
10
"""

Types of variables:  Python supports 2 types of variables
1.       Global variables 2. Local variables
(1.)Global variable: which are declared before the function (or) outside the function is called global variable.
Syntax:
Var=value
def fun():
….


Advantages for global variable:
1.       To declare global variable inside function
2.       To make global variable available to the function so that we can perform required modifications.

Case 1: if global variable is declared and local variable is also same name, then local variable is responded
a=10
def f1():
    print(a)
def f2():
    a=20
    print(a)
"""output:
>>> f1()
10
>>> f2()
20
"""
(2.) Local Variables: The variable 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 the function we can not access it.
def f1():
    print(a)
def f2():
    print(a)
"""output:
>>> f1()
10
>>> f2() error
"""
Sometimes, the global variable and the local variable may have the same name. function by default refers to the local variable and ignores the global variable so, the global variable is not accessible inside the function but outside of it, it is accessible.

a=10#local variable
def f1():
    a=30 #local variable
    print(a)
f1()
print('a=',a)
"""output:
30#local variable
a= 10 #global variable
>>>
"""

Example3: When we wants to use the global variable inside a function, we can use the global keyword before the variable in the beginning of the function.

a=10#global variable
def f1():
    global a
    print(a)#global
    a=30 #Modified global value
    print(a)#modified global value
f1()
print('a=',a) #modified global value
"""output:
10
30
a= 30
>>>
"""
Example 4: when the local and global have same name, when we want to access only global, then globals() function should be used.
a=10#global variable
def f1():
    a=20 #local variable
    x=globals()['a']#global variable into x
    print(x)#global variable
    print(a)#local variable
f1()
print('a=',a) # global value
"""output:
10
20
a= 10
>>>
"""
Related Video: https://www.youtube.com/playlist?list=PL2mD2CO8TKlJdFbbtuhTXPQk2tNQx0pb1
Previous: **kwargs(Keyword arguments)
Next:Recursive Function

1 comment:

Files with Exception handling

#Ask the user to take two input integer values var a,b try:     a=int(input("enter any integer value:"))     b=int(input(...