Python Functions


Introduction to Python Functions

A function in python is a reusable block of code that can be called any number of times.

For example, we want to find the cube of the number. So instead of writing the program again and again, we can create a function and call the function any number of times.

Benefits

  1. Code Reusability : We can create a function once and call it any number of times.
  2. Code Readability: We can divide our complex code into multiple tasks, which will make our code easy to write, read and understand.

Types

  1. Standard library functions: The built-in functions in Python that are directly available for the use are known as the standard library functions. Example, len(), min(), max(), etc
  2. User-defined functions: The functions that are created by the user for the specific functionality are known as user-defined functions.

Creating a Function

We can define the function using the “def” keyword, followed by the function name and then parenthesis. We are supposed to use the colon(:) after the parenthesis, stating that the body of the function is about to start.

In Python, everything is based on indentation, we never use any kind of bracket to define that this is the start of the body and the end of the body, all the content of the body is written after a tab or a space.

Syntax:

def function_name(parameter_1, parameter_2)):
    #function code
    return value
defA keyword used to define a function.
function_nameName of the function.
Parameter(s)Optional. Value(s) we pass to the function. We can pass any number of values.
returnOptional. The keyword used to define that this function will return a value.

Example:

Python Functions

So the functions can exist in different forms:

  • Without parameters
  • With parameters
  • With parameters and return

Let us take a look at an example of each.

Creating a function – Without Parameters.

In [1]:
def function_name():
    print("This is the content of the function.")

With Parameters.

In [2]:
def multiply(x, y):
    result = x * y
    print(result)



multiply(2, 3)
6

With Parameters and return value.

In [3]:
def multiply(x, y):
    result = x * y
    return result



result = multiply(2, 3)
print(result)  
6

Calling a Function

We call the function using the name of the function followed by parenthesis.

Creating a function.

In [1]:
def function_name():
    print("This is the content of the function.")

Calling a function.

In [2]:
function_name()
This is the content of the function.

Return Values

A function can perform its operations and return values. These operations can be anything from simple operation like addition, subtraction, to complex tasks or calculations. The value a function can return can be of any data type, like a simple integer, string, list, dictionary, etc.

We use the return keyword to return a value.

Function to return sum of bonus and salary.

In [1]:
def add_bonus(salary):
    return salary + 100

Calling function and saving returned value in ‘final_salary’ variable

In [2]:
final_salary = add_bonus(10000)
print(final_salary)
10100

Return to stop execution

The return keyword can be used anywhere in the function, i.e. at the end or in between of the function based on the condition. return keyword stops the execution of the function and passes the control back to the calling statement.

Funciton to add bonus of 100 dollar, if salary is greater than 20000, then no bonus, it will return salary as it is.

In [1]:
def add_bonus(salary):
    if salary > 20000:
        return salary
    return salary + 100

Salary with bonus added.

In [2]:
final_salary = add_bonus(10000)
print(final_salary)
10100

Salary without bonus.

In [3]:
final_salary = add_bonus(21000)
print(final_salary)
21000

Return multiple values

We can return multiple values using return. Simply, each value has to be separated by a comma.

In [1]:
def employee_details():
    return 'John',205,20000
In [2]:
name, id, salary = employee_details()
print(name)
print(id)
print(salary)
John
205
20000

Docstring

The Docstring is the short form of a documentation string. We use docstring to define with functionality of the function briefly so that anyone can read this text and understand the function.

We use single triple quotes(”’ ”’) or double triple quotes(“”” “””) to define the docstring.

In [1]:
def cobe_of_two():
    """
    This function return cube 
    of number two.
    """
    return 2**3    
In [2]:
print(cobe_of_two())
8

View docstring using the help function.

In [3]:
help(cobe_of_two)
Help on function cobe_of_two in module __main__:

cobe_of_two()
    This function return cube 
    of number two.

Nested Functions

A function can be created inside another function, this is known as an inner function or nested function. The inner functions can access the variables of the outer function. Basically, the inner function is used to hide from everything happening outside. This is known as encapsulation. Or to divide the function in small chunks.

In [1]:
def calculation(x, y):
    
    def add():
        result = x + y
        print("Addition =",result)
    
    def multiply():
        result = x * y
        print("Multiplication =",result)

    add()
    multiply()


calculation(2, 3)
Addition = 5
Multiplication = 6

Pass Statement

The pass statement is used when we don’t want to write code for the function body. We cannot define a function without any content, but we can use the pass keyword to define an empty function without any code.

Without pass we get an error.

In [1]:
def multiply(x, y):
  File "<ipython-input-1-f528bbd0deca>", line 1
    def multiply(x, y):
                       ^
SyntaxError: unexpected EOF while parsing

Works fine with pass

In [2]:
def multiply(x, y):
    pass

References

  1. Python Inner Functions
  2. Python – Functions