Wednesday, May 11, 2016

A Better Understanding of Function

After discussing the basics of function in my blog some months back in this link - http://cseatglance.blogspot.in/2015/07/introduction-to-function-python.html , I want to emphasize more about function  in this blog entry. So, first start by peruse through the code below, and guess the output -

#function inside function
#!/usr/bin/python

def total(initial=5,*numbers,**keywords):
    count=initial
    for number in numbers:
        count+=number
    for key in keywords:
        count+=keywords[key]

    def total(count):
        count-=10
        print "Inside me",count
        return count
    total=total(count)
    print "the total",total
    return count

print (total(2,10,12,veg=50,lal=45))



can you guess the output of the program? Here we have one function which has a three initial passed argument and inside it we have another function with same name but have only one argument passed. Among the arguments the initial is set to default value of five and then the tricky arguments passed. the first one with one * will take all the positional arguments
from that point till the end  collected as a list called 'numbers'. The ** will take the input collected as dictionary. See the count+=keywords[key] option. Basically the function takes the input as a list and dictionary values and then add them. 


So, when we pass the values we get only the numeric one and add them.  From the program you can see when write the last print statement it calls the the total with three arguments. Then it adds up the inputs and calls the inner function total, which in turns subtract the value of count with 10. 

In this particular program all the values are added by the outer total. then it subtracted by the inner total function. But we retain the value of outer total function and not of the inner one. So, the output of the program will be -

>>Inside me 109
the total 109
119 


 
 


 





















No comments:

Post a Comment

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...