Functions In Python With Examples | FACE Prep

In Python, functions are a block of the organized and reusable set of statements that are used for performing a specific task. In even simpler terms, functions in Python are basic structures that accept inputs, perform certain operations using these inputs and give back the result. However, since the purpose is still not clear in our minds, let us explore further.

 Why do we need functions?

Consider you need to write a code to print the elements of a list whose sum is equal to the given number. 

The list contains 3, 6, 4, 9. You need to print the elements whose sum is equal to 13. Hence, the output will be 4 and 9. So, your code may look something like this,

#program to print elements of a list whose sum is equal to 13 without using function
list1 = [3, 6, 4, 9]
res1 = list1[0] + list1[1]
if(res1 == 13):
    print(list1[0], list1[1])
res2 = list1[0] + list1[2]
if(res2 == 13):
    print(list1[0], list1[2])
res3 = list1[0] + list1[3]
if(res3 == 13):
    print(list1[0], list1[3])
res4 = list1[1] + list1[2]
if(res4 == 13):
    print(list1[1], list1[2])
res5 = list1[1] + list1[3]
if(res5 == 13):
    print(list1[1], list1[3])
res6 = list1[2] + list1[3]
if(res6 == 13):
    print(list1[2], list1[3])
4 9

In this case, the number of lines of code is large & also the same code is being repeated several times. To minimize this, functions come in handy. Using functions, this can be minimized by writing a function to perform the addition operation and calling this function whenever required. Before we arrive at the actual code, let us understand some terminology & aspects related to functions.

 Arguments and Parameters 

Assume you need to complete a task. To do this, firstly, you need to figure out how to do it or get it done and secondly, you need to list down the resources required to complete it. Here, the entire logic to finish the task is what we call the function definition and the resources used to complete it are what we refer to as the arguments

The arguments can be either obtained from the user inside the function definition or inside the main() function. If the arguments are obtained inside the main() function, then those arguments have to be passed to the function definition. 

A parameter is a variable in the function definition which accepts and stores the arguments passed from the main() function. 

A function in Python can be of different types. 

Types of functions in Python

In Python, we have two different types of functions. They are

  • Built-in functions
  • User-defined functions

Python has a set of built-in functions such as print(), bin(), int(), etc. These functions are pre-defined in the Python library to perform some specific tasks. Apart from this, a user can also create his/her own functions and such functions are called user-defined functions. Let us now see how to create a user-defined function.

 Creating a function in Python

Creating functions in Python involves three steps. Let us look at them one by one. 

Step 1: Defining the function (Function Definition)

The function definition contains a set of statements that defines the task or operation to be performed by the function. The syntax to define a function in Python is

def function_name (parameters):
    executable statements

As in the syntax, the function name should proceed with the keyword def and end with a colon. Naming the function is similar to naming variables in Python.

Next, the function can be defined with or without parameters. If it is defined with parameters, then the number of parameters must be the same in number and order as that being passed from the main() function. Also, all the executable statements inside a function must be indented with the same number of spaces or tabs.

Step 2: Calling a function in Python

A user-defined function will be executed only when that function is being called from the main() function. And for a function to be called, remember that it needs to be defined in the first place. If the function is being called before defining it, the interpreter will throw an error.

A function can be called using the below syntax,

function_name (arguments)

Note: If the function is defined with parameters, then we need to pass the arguments to those parameters while calling it.

Step 3: Print/Return the result

The function can either print the result in the same function or return the result to the main() function from where it is being called. Here are some examples explaining each of these cases.

a) Function which prints the result
# function which prints the result 
def add (num1, num):
    res = num1 + num2
#function call happening outside the function
add(5, 5)

Explanation: Here, num1 and num2 are the parameters and 5, 5 are the arguments passed to those parameters.

functions print

b) Function which returns a result
#function definition which returns the result to the main() function
def add (num1, num2):
    return num1 + num2  # returning the result to the main() function
# function calling 
res = add(5, 5)
Print (res)


functions return file

Example of Functions in Python

When discussing the need for functions, we came across a code that prints elements whose sum is equal to 13. Now since we are clear with the concepts of functions, let us see how to rewrite the same code using functions.

#program using function to print elements of a list whose sum is equal to 13
def func(a, b):
    return a + b
list1 = [3, 6, 4, 9]
a = len(list1)
i = 0
while(i < a):
    j = i + 1
    while(j < a):
        res = func(list1[i], list1[j])
        if(res == 13):
            print(list1[i], list1[j])
        j = j + 1
    i = i + 1
4 9

Now, the number of lines of code is comparatively less and the code looks more readable. 

Other Important Concepts Related to Functions

a) Call by reference in Python

In Python, both the parameters and the arguments point to the same memory location. So, any changes made to the parameter inside the function definition are reflected in the arguments of the main() function.

However, there is an exception in the case of mutable objects since the changes made to the mutable objects like string do not revert back to the original string.

In the below example, the list is appended with the elements 5 and 6 inside the function definition and the same has been reflected inside the main() function also.

#defining the function 
def reference(list1): 
    print("List inside function: ", list1) 
list1 = [1, 2, 3, 4] 
#calling the function 
print("List outside function: ", list1)
List inside function: [1, 2, 3, 4, 5, 6]
List outside function: [1, 2, 3, 4, 5, 6]
But in case of strings, the changes made inside the function will not be reflected inside the main() function as shown below.
#defining the function 
def reference(string1): 
    string1 = string1 + "Prep"
    print("String inside function: ", string1)
string1 = "FACE" 
#calling the function 
print("String outside function: ", string1)
String inside function: FACEPrep
String outside function: FACE

 b) Returning multiple values

Python functions have the ability to return multiple values. This can be done by separating the return values with a comma. Generally, Python packs multiple return values in the form of a single tuple and returns it.

Let’s understand better with an example, where the function concatenates the given two strings, repeats the first string two times and returns both the results using a single return statement.

#program that returns multiple values to the main() function in the form of a tuple 
def func(str1, str2):

    return str1 + str2, str1 * 2
res = func("FACE", "Prep")

We can use multiple assignments to unpack the elements of the tuple as shown below.

#program that unpacks multiple return values using multiple variables
def func(str1, str2):

    return str1 + str2, str1 * 2
concat, repit = func("FACE", "Prep")

Here, the result after concatenation is stored in the variable ‘concat’ and the result after repetition is stored in the variable ‘repit’. 

 c) Nested functions in Python

Python allows us to also write one function inside another function. Such functions are called nested functions. The inner function cannot be called directly from the main() function. It can be called through the outer function.

For instance, consider a simple nested function that performs a concatenation operation of two strings, where the inner function is called using the return statement of the outer function.

#nested function
def outer(str1, str2):

    def inner(str3, str4):
        return str3 + str4
    return inner(str1, str2) 
res = outer("FACE", "Prep")
First, the outer function is called from the main() function with the arguments FACE and Prep. These arguments are stored in the parameters str1 and str2 respectively. The outer function calls the inner function using its return statement with the same arguments. Now, ‘FACE’ and ‘Prep’ get stored in the parameters str3 and str4 respectively. After performing the concatenation operation, the inner return statement returns the result to the main() function.

Functions in Python FAQS

Functions are a block of the organized and reusable set of statements that are used for performing a specific task. 

A function is defined using the keyword ‘def’ followed by the function name. The first line of a function definition should end with a colon. The function definition contains a set of executable statements with the same indentation.

A function is called using its name from the main() function. As we already know, the function can be defined with or without parameters. If the function is defined with parameters, then we need to pass arguments to the function definition when calling that function.