Python Basics: Understanding The Functions



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. An 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.
def functionNameHere(parameters):
    #your code here

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 docstring in your function. The Docstring is nothing but just a first-string statement that is processed by doc builders as IntelliSense does.
def functionNameHere(parameters):
    """place your doc string here"""
    #rest of the code.


As you can see in the preceding image, the docstring 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.   

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 "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.
  1. def func1():  
  2.     return "from func1"  
  4. func1Alias=func1  
  5. print(func1)  
  6. print(func1Alias)  
  7. print(func1())  
  8. print(func1Alias()) 
The output will be
<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.
return data_to_return
  1. def func1():  
  2.     return "from func1 return statement"  
  3.     return  
  5. 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:
  1. def person1():  
  2.     "This is a doc string"  
  3.     def person2():      #inner function  
  4.         return "Work Done!"  
  5.     return person2      #returning inner function  
  6. print ("calling person1 for work: "+ str(person1()))  
  7. print("person1 called person2: "+str(person1()()))  #calling inner function 
calling person1 for work: <function person1.<locals>.person2 at 0x02A331E0>
person1 called person2: Work Done!

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.
  1. def func1(a=2,b=4,c=2,d=4): #defaults are assigned using = operator.  
  2.     return a+b+c+d  
  4. print(func1())  
  5. print(func1(1,2))  
  6. print(func1(1,2,3,4)) 

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 argument. It is just a way of calling the function by passing the values to some of the parameters and not necessarily in sequence.
  1. def func1(a=2,b=4,c=2,d=4):  
  2.     return a+b+c+d  
  4. print(func1())  
  5. print(func1(a=1,d=2))  #keyword arguments are a=1 and d=2 

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.
  1. def func1(*name,opr="+"):  
  2.     res=0  
  3.     for num in name:  
  4.         res += num  
  5.     return res/len(name)  
  6. print(func1(1,2,3,4,5,6,7))  
  7. print(func1(5,5))  
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.
lambda parameters:data
  1. print((lambda x,y:x+y)(4,5))

Example of functions and flow control
  1. #Function demo  
  4. def performOpr(*nums,opr="+"):  
  6.    def doAdd(*nums):  
  7.         temp=0  
  8.         for num in nums:  
  9.             temp += int(num)  
  10.         return temp  
  12.    def doSub(*nums):  
  13.         temp=0  
  14.         for num in nums:  
  15.             temp -= int(num)  
  16.         return temp          
  18.    def doMultiply(*nums):  
  19.         temp=1  
  20.         for num in nums:  
  21.             temp *= int(num)  
  22.         return temp          
  24.    def doDiv(*nums):  
  25.         temp=1  
  26.         for num in nums:  
  27.             temp /= int(num)  
  28.         return temp     
  30.    if opr=="+":  
  31.        return doAdd(*nums[0])  
  32.    elif opr=="-" :  
  33.         return doSub(*nums[0])  
  34.    elif opr=="*" :  
  35.        return doMultiply(*nums[0])  
  36.    elif opr=="/" :  
  37.        return doDiv(*nums[0])  
  41. while(True):  
  42.     print("Choose option :")  
  43.     print("1. Addition")  
  44.     print("2. Subtraction")  
  45.     print("3. Multiplication")    
  46.     print("4. Division")  
  47.     print("Enter q to exit")  
  48.     choice=input()  
  49.     if choice=="1":  
  50.         numlist=[]  
  51.         print("Enter numbers or Q to finish")  
  52.         while(True):  
  53.             numlist = list(input().split(sep=" "))  
  54.             if "q" in numlist:  
  55.                 numlist.pop();  
  56.                 print("The result of addition is: "+str(performOpr(numlist)))  
  57.                 break  
  59.     elif choice=="2" :  
  60.         numlist=[]  
  61.         print("Enter numbers or Q to finish")  
  62.         while(True):  
  63.             numlist = list(input().split(sep=" "))  
  64.             if "q" in numlist:  
  65.                 numlist.pop();  
  66.                 print("The result of subtraction is: "+str(performOpr(numlist,opr="-")))  
  67.                 break  
  68.     elif choice=="3" :  
  69.         numlist=[]  
  70.         print("Enter numbers or Q to finish")  
  71.         while(True):  
  72.             numlist = list(input().split(sep=" "))  
  73.             if "q" in numlist:  
  74.                 numlist.pop();  
  75.                 print("The result of multiplication is: "+str(performOpr(numlist,opr="*")))  
  76.                 break  
  77.     elif choice=="4" :  
  78.         numlist=[]  
  79.         print("Enter numbers or Q to finish")  
  80.         while(True):  
  81.             numlist = list(input().split(sep=" "))  
  82.             if "q" in numlist:  
  83.                 numlist.pop();  
  84.                 print("The result of division is: "+str(performOpr(numlist,opr="/")))  
  85.                 break  
  86.     elif choice=="Q" or choice=="q":  
  87.         print("Thanks for using.")  
  88.         break   
  89.     else:  
  90.         print("Bad choice! :( try again!"


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.

Similar Articles