Python Basics: Understanding The Functions

Slide1.JPG

Introduction

In this article we will learn about functions in Python. We will learn how to create functions in the Python language and how to call the functions. At the end of the article you will be able to create a program that uses functions. This article is divided into sections so that we can understand functions better. The following are the sections:

  1. What a function is
  2. Defining a function in Python
  3. Adding a docstring in Python
  4. Function execution
  5. Function Assignment
  6. Return from function
  7. Inner function
  8. Default values of function parameters
  9. Keyword argument
  10. Arbitrary number of arguments
  11. Lambda expression

What a function is

A function is a part of your code for doing some specific task and whenever you want to perform that task you can use that function. It provides your code a better abstraction. You can design your program using one function at a time. Let's say you want to detect the speed of a car. For that you can create a function, say getSpeedOfCar(). Now whenever you want to detect the car speed you just call this function and your task will be done. Once you have created your function you can use it any number of times. You are no longer required to write the same lines again and again.

Defining function in Python

Defining a function in Python is very easy. You just need to place the def before any name and provide it some block scope.

Syntax

def functionNameHere(parameters):

    #your code here

Slide3.JPG

def is used for telling the interpreter that it is a user defined function. It is an abbreviation of define. The function name is any meaningful name given to the function that will be used for accessing it or calling it.  Parameters are the variables passed to functions that change the result of a function. Parameters are very important and they are very much responsible for controlling the behavior of a function.

Adding docstring in function

If you want to add the explanation of your function then you need to add a doc string in your function. The Doc string is nothing but just a first string statement that is processed by doc builders like intellisense does.

Syntax

def functionNameHere(parameters):

    """place your doc string here"""

    #rest of the code.

Slide4.JPG

Slide5.JPG

As you can see in the preceding image, the doc string makes the function task clear and it is very useful for traversing the documentation.

Function execution

We need to call our function to begin execution. A function is called using its name and with the parameters in parenthesis. As soon as you call your function, the function begins executing the statements written in it. But before executing the statement Python must do some bookkeeping for the function variables. As the function executes, it introduces the new symbol table for keeping the record of local variables of the function. Whenever any assignment to the symbol is done the value is stored in a local symbol table . Whenever any reference to a symbol is made, or you can say whenever the symbol value is accessed, it first looks for the value in the local symbol table, then it goes to the local symbol table of the enclosing function and then it is looked for in the global symbol table and if it is not found so far then it checks for built-iin names. So the assigned value is kept in a local symbol table, that prevents us from changing the global variable directly.   

Slide6.JPG

All the parameters passed to a function are kept in a local symbol table of that function. Thus the parameters are passed by value but the symbols are themselves an object reference so it will be more appropriate if we call it as "pass by object reference". The other point to note here is that each def statement introduces a new entry in the symbol table for storing the function symbol itself. The value of that symbol is a user-defined function. That's why I merged the table 2 and table 3 in the preceding picture.

Note: To modify the global variable you need to use the global statements. If you assign a value to a global variable without a global statement then it will not alter the original global variable, it will instead create a new local variable.

Slide7.JPG

Function Assignment

In Python you can assign a function to a variable in the same way as you assign a value to it. You can even use those variables to call the function as well. The function itself is a name that holds the value of the user-defined function.

def func1():

    return "from func1"

 

func1Alias=func1

print(func1)

print(func1Alias)

print(func1())

print(func1Alias())

The output will be

<function func1 at 0x029F31E0>
<function func1 at 0x029F31E0>
from func1
from func1

Slide8.JPG

Return in function

Return means the task is done and now you need to return from where you came with the specified data. It is the last statement executed by a function. You can return any type of data, you can even return a function. If the function fails to execute the return statement then it will return nothing and if there is data with the return then it will also return none.

Syntax

 

return data_to_return

 

Example

 

def func1():

    return "from func1 return statement"

    return

 

print(func1())


Slide9.JPG

 

Inner function

In Python it is possible to declare a function inside a function. These functions are known as inner functions. It's the same as when you pass your work to someone else and he also passes it to someone else. You can also return the inner function and not only that you can even call it. Let's see how in the following:

 

def person1():

    "This is a doc string"

    def person2():      #inner function

        return "Work Done!"

    return person2      #returning inner function

print ("calling person1 for work: "+ str(person1()))

print("person1 called person2: "+str(person1()()))  #calling inner function

 

Output:

 

calling person1 for work: <function person1.<locals>.person2 at 0x02A331E0>
person1 called person2: Work Done!
 

Slide2.JPG
 

Default values of function parameter

 

Sometimes we need some parameters to take the default values if the user didn't supply them. It is very useful, especially if your function has many arguments. In that case you can assign a default value for some of your parameters and allow the user to call your function in a sorthand manner. The parameters should be in order.

 

def func1(a=2,b=4,c=2,d=4): #defaults are assigned using = operator.

    return a+b+c+d

 

print(func1())

print(func1(1,2))

print(func1(1,2,3,4))

 

Slide11.JPG

 

Note: In case of a mutable sequence like lists, the number of calls matters a lot if the function is modifying the parameter. The defaults are calculated only once and after that the modified sequence is used for default values. So if you are dealing with lists in parameters and assigning them some default values then keep this note in mind.

 

Keyword argument

 

Now that we are familiar with default arguments, there is another keyword or kwarg arguments. It is just a way of calling the function by passing the values to some of the parameters and not necessarily in sequence.

 

def func1(a=2,b=4,c=2,d=4):

    return a+b+c+d

 

print(func1())

print(func1(a=1,d=2))  #keyword arguments are a=1 and d=2

 

Slide12.JPG


Passing any number of parameters

 

Assume the situation where you are making a calculator average function but the user can pass any number of arguments to your function. So how to do that? For these kinds of situations we have "*args" in which you can pass any number of parameters.

 

def func1(*name,opr="+"):

    res=0

    for num in name:

        res += num

    return res/len(name)

print(func1(1,2,3,4,5,6,7))

print(func1(5,5))

 

Slide13.JPG

 

 

Anonymous functions or Lambda form

 

In Python you can create functions without a name. That's why they are called anonymous functions.  We create these functions using a lambda statement; that's why they are also known as lambda expressions. In a lambda expression, on the left side we have parameters and on the right side we have the working of the function.

 

Syntax

 

lambda parameters:data

 

print((lambda x,y:x+y)(4,5))

 

lambda.jpg

 

Example of functions and flow control

 

#Function demo


 

def performOpr(*nums,opr="+"):

 

   def doAdd(*nums):

        temp=0

        for num in nums:

            temp += int(num)

        return temp

 

   def doSub(*nums):

        temp=0

        for num in nums:

            temp -= int(num)

        return temp        

 

   def doMultiply(*nums):

        temp=1

        for num in nums:

            temp *= int(num)

        return temp        

 

   def doDiv(*nums):

        temp=1

        for num in nums:

            temp /= int(num)

        return temp   

 

   if opr=="+":

       return doAdd(*nums[0])

   elif opr=="-" :

        return doSub(*nums[0])

   elif opr=="*" :

       return doMultiply(*nums[0])

   elif opr=="/" :

       return doDiv(*nums[0])

 

 

 

while(True):

    print("Choose option :")

    print("1. Addition")

    print("2. Subtraction")

    print("3. Multiplication")  

    print("4. Division")

    print("Enter q to exit")

    choice=input()

    if choice=="1":

        numlist=[]

        print("Enter numbers or Q to finish")

        while(True):

            numlist = list(input().split(sep=" "))

            if "q" in numlist:

                numlist.pop();

                print("The result of addition is: "+str(performOpr(numlist)))

                break

           

    elif choice=="2" :

        numlist=[]

        print("Enter numbers or Q to finish")

        while(True):

            numlist = list(input().split(sep=" "))

            if "q" in numlist:

                numlist.pop();

                print("The result of subtraction is: "+str(performOpr(numlist,opr="-")))

                break

    elif choice=="3" :

        numlist=[]

        print("Enter numbers or Q to finish")

        while(True):

            numlist = list(input().split(sep=" "))

            if "q" in numlist:

                numlist.pop();

                print("The result of multiplication is: "+str(performOpr(numlist,opr="*")))

                break

    elif choice=="4" :

        numlist=[]

        print("Enter numbers or Q to finish")

        while(True):

            numlist = list(input().split(sep=" "))

            if "q" in numlist:

                numlist.pop();

                print("The result of division is: "+str(performOpr(numlist,opr="/")))

                break

    elif choice=="Q" or choice=="q":

        print("Thanks for using.")

        break 

    else:

        print("Bad choice! :( try again!")

 

 

Output

 

op.jpg

 

Summary

 

Now we completed the functions and I hope you like the article. I tried to keep the codes short and consistent. If you want to master it then start practicing it. At the end I just want to say, don't forget to provide your suggestions. If you like the article then you can share it .

 

Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all