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

Tuesday 26 November 2019

**kwargs(Keyword arguments)


   **kwargs(Keyword arguments):

Example 1:
def f1(*a):
    print("a=",a)
#*args=("Hyd","vij","Kadapa")#creating tuple and storing into args var
f1(5) #valid output: a=5 since we can send non keyword argument
f1(a=5)#error we can not send keyword argument to the function

Example 2:
def f1(**args):
    print("a=",args)
#f1(5)# error due to non keyword argument
f1(a=5)#valid as it is keyword output: a={1,5} in the form of dictionary

Python passes variable length non keyword argument to the function using *args but we cannot use this to pass keyword argument. For this problem Python has got a solution called **kwargs, it allows us to pass the variable length of keyword arguments to the function.
We use the double asterisk ** before the argument (parameter). The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk **.

Example 3: Using **kwargs to pass the variable keyword arguments to the function

def student(**data):
    print("\nData type of argument:",type(data))
    for key, value in data.items():
        print("{} is {}".format(key,value))
student(name="Sita", Age=22, Phone=1234567890)
#student(name="Ram", Email="ram@gmail.com", course="MCA", Age=25, Phone=9876543210)
"""output:
Data type of argument: <class 'dict'>
name is Sita
Age is 22
Phone is 1234567890
>>>
"""
*args and *kwargs are special keyword which allows function to take variable length argument.
*args passes variable number of non-keyworded arguments list and on which operation of the list can be performed.
**kwargs passes variable number of keyword arguments dictionary to function on which operation of a dictionary can be performed.
*args and **kwargs make the function flexible.

def display(a,** kwarg):#**kwarg can take 0 or more values to display given values
    print("fp",a)
    for i,j in kwarg.items():
        #items() gives pairs of item
        print('key={},value={}'.format(i,j))
"""
Insteag of kwarg,we can give any identifier
output:
1. >>> display(2,rno=5)
fp 2
key=rno,value=5
>>> 
2.>>> display(3,rno=4,name='ramesh')
fp 3
key=rno,value=4
key=name,value=ramesh
>>>

"""
In Python Dictionary, items() is used to return the list with all dictionary keys and values.

Syntax: dictionary.items()
Parameters: This method takes no parameters.


str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting.



You may like the following posts:
Formal and actual parameters


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(&qu...