Understanding The Functions in Python

Functions in Python
Functions in Python

Introduction To Functions in Python

Let’s understand Functions in Python with an example:

Consider that you, along with three of your friends are given the responsibility of implementing the ERP (Enterprise Resource Planning) system for your university from scratch. There are only four modules: Results, Time-Table, Fees-Section, and Examination-Form.

The university administrator is quite strict and wants the students to view their marks, check the timetable, pay examination fees, and submit the examination form if and only if their attendance is above 80%.

Since you are a team of four members, each member works independently on the Result Module, Time-table module, Finance Module, and Examination Module. Now, as per the administrator’s requirements, there needs to be a check for attendance in each of these modules.

There are two ways to check for attendance criteria:-

You could either do attendance checks for every module independently.

Proceeding this way will involve implementing the same logic over and over again in different modules. This will be time-consuming as well as reduces the readability of the code.

Here Functions in Python come to the rescue. Using functions, you could implement the attendance logic once and can reuse it many times as and when required.

You could write a function that will check for students’ attendance and will return true if the attendance is above 80% else, it will return false. This function can now be called in different modules independently.

simple_erp
Simple ERP Implementation

Proceeding this way will reduce the time taken to implement the same logic again and again and improve your team’s efficiency.

Clearly, the second approach is far better than the first one. 

blog banner 1

We will study more about Functions in Python in this blog. Do check the full blog to have a clear understanding of Functions.

Functions in Python

function_python
Functions in Python

A function is an organized block of code that performs a specific task like computational, logical, or evaluative tasks and is executed only when explicitly called. The data passed to a function is called as Parameters of a function.

The idea is to put the code of the repeatedly executing task together as a function so that instead of writing the same logic over and over again, you only need to call the function.

Functions are used for making the code more efficient, organized, modular, and concise.

Even if you are a novice Python programmer, you still have used the function many times. Remember the print() function used for printing purposes and input() function for taking user-input. These two functions are the most commonly used built-in functions.

How to create a Function in Python?

To define a function in Python, you need to follow a set of simple rules.

  • Function blocks in Python begin with the keyword “def” followed by the name of the function and the parameters of the function placed in parentheses(()). Function names should follow the naming convention of Python identifiers.
  • A colon (:) to mark the end of a function header.
  • A tab space indentation is done after specifying the function name. All the statements indented equally after the function name are considered to be a part of the function.
  • The first statement inside a Python function has to be a docstring or documentation string . A docstring contains information regarding what the function does. Specifying a docstring is optional but is considered a good practice to do so.
  • The function body usually contains the code of the task the function is intended to perform.
  • An optional return statement to return a value from the function to the caller.
function_synatx
Function syntax

Python Docstrings provide a convenient way of associating documentation with Python functions, classes, and methods. The docstrings can be declared either using “`triple single quotes“` or “““triple double quotes“““ just below the function declaration.

The docstrings can be accessed using __doc__ method. If there are multiple lines within the docstring, the second line should be left blank, and the first line should be a short description.

Let’s try to understand Function in Python with a simple example of the addition of two numbers wherein the result will be returned to the caller as follows

# function declaration in Python
def add(a, b):
    ''' This is a docstring
    
       This function is used for addition of two numbers
       '''
    c = a + b
    return c
 
print(add(10, 20))  # Calling the function
print(add(10.5, 24.5))
 
# Access the docstring specified above
print(“Accessing docstring using help function”)
help(add)

The output will be

30
35.0
Accessing docstring using help function
Help on function add in module __main__:

aadddd(a, b)
    This is a docstring
    
    This function is used for addition of two numbers

Remember, the arguments in the function call are positional arguments. This means that the first argument in the function call is used as the value of the first parameter and the second argument in the function call is used as the value of the second parameter.

Refer to the below program for clarity:

Positional_arguments
Positional arguments

Calling a Function

Python programs are usually executed sequentially i.e., one instruction is executed only after the previous one has completed its execution. Whenever any function is called, the control gets transferred to that function. A python function can be called from another function, program, or directly from a Python prompt.

To call a function, simply type the function name and pass the parameters to it. The return statement is usually present in the function and is used to return a specific value or data item to the caller. If the return statement does not consist of a variable, an expression, or a constant, a None object is returned.

# This functions returns the multiplication of two numbers
def multiply(a, b):
    return a * b
 
# This function simply prints the string passed to it as a parameter
# None is returned from the function
def printMe(str):
    print(str)
 
print(multiply(2, 3))
printMe("Functions in Python")

The output will be

6
Functions in Python

Pass by reference vs. Pass by Value

The values that are passed in the function call are called actual parameters, and the values received by the function are called the formal parameters.

In the example above, a and b are the formal parameters in the multiply function, while 2 and 3 are the actual parameters.

In pass-by-value, a copy of the actual parameter’s value is made in the memory, i.e., now there will be two independent variables with the same value. Whereas in the pass by reference means to pass the reference of an argument to the calling function, i.e., the caller and the called function both share the same variable as the parameter. 

Pass_by_reference_pass_by_Value
Pass by reference vs. Pass by Value

In Python, all the parameters are passed by reference. If there is any change in the parameter value inside the function, that change will be reflected back in the calling function.

The below example illustrates the same.

def printList(myList):
    '''This function will print the list of strings being passed to it'''
    print("Printing the List: ", myList)
    myList.append("Functions in Python")
 
    print("Printing the List: ", myList);
    return
 
 
myList = ["Coding Ninjas", "CodeZen"]
printList(myList)
 
print("Printing the list outside the function: ", myList)

Output:

Printing the List:   ['Coding Ninjas', 'CodeZen']
Printing the List:   ['Coding Ninjas', 'CodeZen', 'Functions in Python']
Printing the list outside the function:  ['Coding Ninjas', 'CodeZen', 'Functions in Python']

It can be observed from the example above, if the parameters were not passed by reference, the change in the list would not be reflected outside the function.

Types of Functions

There are three types of functions in Python:

Built-in functions

Python interpreter has various predefined functions that are readily available to use. We don’t have to define these functions to use them; we can directly call them. These functions are called built-in functions.

Built-in functions are packaged together into a module. These modules are packaged together to form a library. 

build_in_function
Built-in functions

Python has a wide range of built-in functions available. For further information, check out the official documentation.

User-defined functions

Functions that the programmer defines to perform a specific task are called user-defined functions.

Examples: printList() function implemented in the above example.

Consider an example below that involves both in-build and user-defined functions:

import math
 
# This function is a user-defined function
def powerMultiplication(a, b):
 
    # Using built in function pow() for calculating power 
    # of 'a' to the power of 2.
    power = math.pow(abs(a), 2)
 
    # Multiplying the power with 'b'
    power = power * abs(b)
    return power
 
 
print(powerMultiplication(7, 9))
print(powerMultiplication(8, 4))

In the example above powerMultiplication() is a user-defined function while math.pow() and abs() is a built-in function

441
256

Anonymous Function:

Any function without a name is called an Anonymous function or Lambda function. As in the case of normal function, the def keyword is used. Similarly, the lambda keyword is used to define anonymous functions in Python.

The syntax is as follows

 lambda arguments: expression

Lambda functions are syntactically restricted to a single expression, and the function can have any number of arguments being passed to it.

sum = lambda arg1, arg2: arg1+arg2
 
print(sum(45, 55))
print(sum(56, 78))

The output will be

100
134

Memory Management

Python is a high-level programming language. Memory management in Python involves a private heap containing all Python objects and data structures. The management of this private heap is ensured internally by the Python memory manager.

Methods and variables are usually created in Stack Memory; a new stack frame is created whenever a function is called. And whenever the method execution stops/completes the stack frame is destroyed.

Do check out the official documentation for more information.

Function Arguments

Information is passed to a function as arguments. Many people tend to confuse between parameters and arguments.

In general, a parameter is a variable that is listed inside the parenthesis in the function definition, while arguments are the values that are sent to the function when it is called.

Parameters and arguments

We can call a function in Python using the following types of formal arguments.

Required Arguments – 

The arguments passed to a function in correct positional order are called as required arguments.

The number of arguments in the function call should match the number of parameters specified in the function definition.

Keyword Arguments – 

Those arguments which when passed to a function are identifiable by specific parameter names are called Keyword arguments. In Python, we can change the order of the arguments when calling the function using keyword arguments.

Using keyword arguments, we can skip some arguments or place them out of order. In nutshell, consider keyword arguments as sending arguments in key = value syntax.

Consider an example to understand how using keyword arguments, we can change the order of arguments passed to the function

def printMe(name, course):
    print(name, " is studying ", course)
 
 
printMe(name = "ABC", course="OS")  
printMe(course="DBMS", name="DEF") 

The output will be

ABC is studying OS
DEF is studying DBMS

Default Arguments

If you don’t specify an argument value in the function call, it will result in an error by default. However, using a default value for such parameters in the function definition will prevent the error.

         The argument then takes up the default value if a value is not specified in the function call.

def multiply(a, b = 56):
    return a * b
 
 
print(multiply(2, 3))  # Here, we are passing the arguments in the order
print(multiply(5))  # Here, we are passing a single argument, so the second argument will
# take the default value of 56
 
print(multiply(b=3, a=2))  # Here we are using Keyword arguments

The output will be

6
280
6

Variable-length arguments

Sometimes we may not know in advance the number of arguments that need to be passed to a function. This type of situation is handled effectively in Python using Variable-length arguments or Arbitrary arguments.

Use (*) before the parameter name to denote variable-length arguments in the function definition.

def greetme(*names):
    ''' This function greets all the persons in the names tuple'''
    for name in names:
        print("Hello, " + name)
 
greetme("Tom", "Bob", "Alice")
greetme("Tom", "Bob", "Alice", "Jenny")

Frequently Asked Questions

What are functions in Python?

A function in Python is a block of statements intended to perform a specific task (logical, computational, and conditional task) and is executed only when explicitly specified.

There are two types of functions in Python, namely, built-in functions and user-defined functions.

#An example function to compare two numbers and return
#the greater of the two
def compare(a, b):
if(a > b):
return a
return b
Python functions are used to group similar blocks of code together. It provides the reusability of code.

How many Python functions are there?

As per official documentation, Python has 69 built-in functions.

What are the two main types of functions?

Functions in Python can be divided into the following two categories:-
1. In-built functions: Those functions already defined in Python libraries and can be used directly are called in-built or pre-defined functions.
Example: abs(), pow(),bool() etc.
There are 69 built-in functions in Python.

2. User-defined functions: The functions defined by the programmer to perform a specific task are called user-defined functions.

What are Python built-in functions?

Those functions which are already defined in Python libraries and can be used directly are called in-built or pre-defined functions.

Key Takeaways

This article aimed to explain functions in Python and the different types of functions available in the Python programming language.

With this done, now you have a clear understanding of functions in Python. You may now figure out more details about functions in Python, explore more and more about in-built functions. 

Don’t forget to upgrade yourself by reading some awesome articles and other curated study material available on Codestudio.