Saturday, June 16, 2018

python chap 12 (hi friends checkout my previous lessons to learn from start)

Function

It is also possible to define function with variable number of arguments this are the forms as

Default Argument Values

  In here we specify a default value for one or more arguments this how we can call a function with fewer arguments this creates a function that can be called with fewer arguments than it is defined to allow like :


def myfun(fight,leavestep = 4, sail = 'boat'):
    while True:
        ok = input(fight)
        if ok in ('sword','knife','gun'):
            return True
        if ok in ('no','pain','gain'):
            return False
        if leavestep <= 0:
            raise ValueError ('invalid user response')
        print(sail)         
The function can be called in several ways such as
  • giving only mandatory argument like myfun('tool to fight') :
>>> myfun('tool to fight')
tool to fight sword
True
  • or we can give one of the optional arguments like in here myfun('tool to fight',1):
>>> myfun('tool to fight',1)
tool to fightno
False
  • or even giving all the arguments as as myfun('tool to fight',1,'ship')

>>>myfun('tool to fight',1,'ship')
tool to fight
ship
Now here are given the ways first we give the first compulsary argument because in the function it is only without value so we have to give it a value in calling function and by running the code and writing the input we get the values as the process in the function and also can apply all three arguments can also get errors according to the value in the second argument we get as for example here is myfun('tool to fight',0,'ship')
>>> myfun('tool to fight',0,'ship')
tool to fight
Traceback (most recent call last):
  File "<pyshell#46>", line 1, in <module>
    myfun('tool to fight',0,'ship')
  File "<pyshell#38>", line 10, in myfun
    raise ValueError ('invalid user response')
ValueError: invalid user response
Note: The default value are evaluated at the function definition at the defining scope so that

>>> i = 5
>>> def by(arg = i):
    print(arg)

  
>>> i = 7
>>> by()
5
>>>
it will output 5
This here one thing to note as Warning : is that the due to the fact that default value is evaluated only once so in the case of mutable objects such as lists dictionaries or instances of most classes the following function accumulates the arguments passed to it on subsequent calls as

>>> def f(a,L=[]):
    L.append(a)
    return L

>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]
>>>
The result will be as given above to prevent from the default to be shared between subsequent calls you can write the function like this instead and the result will be also as given below
>>> def f(a,L=None):
 if L is None:
  L=[]
  L.append(a)
  return L

 
>>> print(f(1))
[1]
>>> print(f(2))
[2]
>>> 

Keyword Arguments

The keyword arguments are used to call functions in the form as kwargs = value for instance the function is given below

 def plane (power,state = 'a big',action = 'fly high',type = 'sea blue'):
    print("This place will",action,end='')
    print("if you put",power,"power through it")
    print("__ So swift , the",type)
    print("It's",state , "!")
Accepts one required argument power and optional three arguments like state , action, type we can call this function in any of the following ways like
//1 positional argument
plane(1000)
//1 keyword argument
plane(power=1000)
//2 keyword argument
plane(power=1000,action='fly low')
//2 keyword argument
plane(action = 'fly low',power=1000)
//3 positional arguments
plane('thousand','jumbo','fly low')
//1 positional and 1 keyword argument
plane('a ten thousand',state ='jumbo' )

but there are also some invalid calls like

//no compulsary argument
plane()
//non keyword argument after a keyword argument
plane(power=2000,'fly jump')
//duplicate value for the same argument
plane(2000,power=1000)
//unknown keyword argument
plane(speed = 12)
And in the final formal parameter in the form **name receives a dictionary containing all keyword arguments except for those corresponding to a formal parameter and the formal parameter of the form *name may be combined with this which receives a tuple containing the positional arguments beyond the formal parameter list (*name must occur before **name) as

def grocery(kind,*quantity,**price):
    print("-- Do you have any ",kind,"?")
    print("--- Iam sorry we are all out of",kind)
    for arg in quantity:
        print(arg)
    print('-'* 40)
    for kw in price:
        print(kw,":",price[kw])
//result will be as
 grocery("broccoli",3,4,5,broccoligrade1 = 25,broccoligrade2 = 35,broccoligrade3 = 45)
-- Do you have any  broccoli ?
--- Iam sorry we are all out of broccoli
3
4
5
----------------------------------------
broccoligrade1 : 25
broccoligrade2 : 35
broccoligrade3 : 45

the point here to note is that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call


Thats all for this post guys hope you like it to get latest lessons follow by email and share if you want to know more about other languages and my other works or have any doubts please follow and comment below

No comments:

Post a Comment