Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Python

Python Basics: Understanding the Functions

5.00/5 (5 votes)
4 Oct 2013CPOL6 min read 37.6K  
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.

663452/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 is a function?
  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 is a Function?

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:

JavaScript
def functionNameHere(parameters):
    #your code here

663452/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:

JavaScript
def functionNameHere(parameters):
    """place your doc string here"""
    #rest of the code.

663452/Slide4.JPG

663452/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-in names. So the assigned value is kept in a local symbol table, that prevents us from changing the global variable directly.

663452/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 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.

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.

JavaScript
def func1():
    return "from func1"

func1Alias=func1
print(func1)
print(func1Alias)
print(func1())
print(func1Alias())

The output will be:

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

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

JavaScript
return data_to_return

Example:

JavaScript
def func1():
    return "from func1 return statement"
    return
print(func1())

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:

JavaScript
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!

663452/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 shorthand manner. The parameters should be in order.

JavaScript
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))

663452/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.

JavaScript
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

663452/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 do we do that? For these kinds of situations, we have "*args" in which you can pass any number of parameters.

JavaScript
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))

663452/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

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

663452/lambda.jpg

Example of Functions and Flow Control

#Function demo

JavaScript
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

663452/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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)