Python Functions

In python, function is a block of code, and it will contain a series of statements to execute whenever it is called in the program.

 

In python, functions are useful to reduce code duplication and improve code reusability. For example, if you want to execute the same block of statements in multiple places, you can create one function with the required statements and use it wherever required in your application.

Function Syntax

To define a function in python, you need to use the def keyword followed by the function name and parentheses ( ). Following is the syntax of defining the function in python.

 

def function_name(parameters):
    """docstring"""
    statement(s)
    ...
    ...
    return [expr]

If you observe the above function syntax, we used different components to define the function.

 

  • The def keyword is used to indicate the start of the function.
  • function_name is the name to uniquely identify the function.
  • parameters are optional, and we use the parameters to send values to the function.
  • The colon (:) symbol is used to indicate the start of the code block.
  • docstring is optional, and it is useful to provide information about the function.
  • statement(s) inside the function body to perform the required tasks, and the statements must follow the same indentation.
  • The return statement is useful to return a value from the function, and it’s optional. 

To create a block of statements inside of the function body, you need to follow the same indentation for all the statements. To know more about specifying the indentation in python, refer to Python basic syntaxes.

Function Example

Following is the example of creating and calling a function to execute the block of statements in python.

 

def userdetails():
    ''' Function to get user details'''
    name = "Suresh Dasari"
    location = "Hyderabad"
    print("Name: {}".format(name))
    print("Location: {}".format(location))

userdetails()
print("Learn Python")

If you observe the above example, we created the userdetails() function without specifying any parameters.

 

When you execute the above python program, you will get the result as shown below.

 

Name: Suresh Dasari
Location: Hyderabad
Learn Python

Function with Parameters

In python, you can create the functions to receive one or more parameter/argument values based on functional requirements.

 

Following is the example of creating the function with required parameters/arguments in python.

 

def userdetails(name, location):
    ''' Function to get user details'''
    print("Name: {}".format(name))
    print("Location: {}".format(location))

userdetails("Suresh Dasari", "Hyderabad")
print("Learn Python")

If you observe the above example, we created the userdetails function with two parameters (name, location) to receive the values as function arguments.

 

When you execute the above python program, you will get the result as shown below.

 

Name: Suresh Dasari
Location: Hyderabad
Learn Python
Note: The terms both parameters and arguments will refer to the same thing. These are useful to pass the information to the functions.

Function with Default Parameter Values

In python, you can create a function with parameters by assigning default values. The parameters with default values can be omitted while calling the function.

 

While calling the method, if no argument is sent for the default value parameters, it will consider using the default value otherwise, it will use the argument value that is sent for that parameter.

 

Following is the example of creating the function with default parameter values in python.

 

def userdetails(name, location="Hyderabad"):
    '''Function to get user details'''
    print("Name: {}".format(name))
    print("Location: {}".format(location))

userdetails("Suresh")
userdetails("Rohini", "Guntur")

If you observe the above example, we created a function with default parameter values, and we omitted to send values to the default value parameters.

 

When you execute the above python program, you will get the result as shown below.

 

Name: Suresh
Location: Hyderabad
Name: Rohini
Location: Guntur

If you observe the above result, the default value parameters are considered using the default value if no argument is sent otherwise, it uses the argument value that is sent for that parameter.

 

While creating the functions with default parameter values, you need to make sure that the default value parameters are defined at the end of all required parameters otherwise, you will get an exception like “non-default argument follows default argument”.

 

The following is an example of creating a function with default value parameters before the required value parameters in python.

 

def userdetails(location="Hyderabad", name):
    '''Function to get user details'''
    print("Name: {}".format(name))
    print("Location: {}".format(location))

userdetails("Suresh")
userdetails("Rohini", "Guntur")

If you observe the above example, we created a function with default value parameters before the required parameters.

 

When you try to execute the above python program, you will get the exception as shown below.

 

non-default argument follows default argument

Function with Keyword Arguments

Generally, while calling the functions you need to pass the arguments in the same function definition sequence. If you use keyword arguments, you don’t need to worry about the order of arguments while calling the function.

 

The keyword arguments will map argument values to the right parameter based on the argument name. So, while calling the function you can send the arguments in any sequence.

 

Following is the example of using keyword arguments while calling the function in python.

 

def userdetails(name, location):
    '''Function to get user details'''
    print("Name: {}".format(name))
    print("Location: {}".format(location))

#keyword arguments
userdetails(location = "Hyderabad", name="Suresh Dasari")

If you observe the above example, we changed the order of arguments while calling the function with keyword arguments.

 

When you execute the above python program, you will get the result as shown below.

 

Name: Suresh Dasari
Location: Hyderabad

While calling the functions with keyword arguments, you need to make sure that the keyword arguments must follow the positional arguments otherwise, you will get an exception like “positional argument follows keyword argument”.

 

Following is the example of calling the function with keyword arguments in python.

 

def userdetails(name, location):
    '''Function to get user details'''
    print("Name: {}".format(name))
    print("Location: {}".format(location))

userdetails(location = "Hyderabad", "Suresh Dasari")

If you observe the above example, we call the function with keyword arguments before the positional arguments.

 

When you try to execute the above python program, you will get the exception as shown below.

 

positional argument follows keyword argument

Function with Arbitrary Arguments

When you are unsure about the number of arguments sent to the function, the arbitrary arguments are useful to handle the situation.

 

To handle the number of arguments dynamically, you need to add an asterisk (*) before the parameter name in the function definition, and we will call it arbitrary arguments. When you define arbitrary arguments in the function definition, it will receive arguments as a tuple object.

 

Following is the example of defining the arbitrary arguments in the function definition to handle the arguments dynamically in python.

 

def userdetails(*users):
    '''Function to get user details'''
    for user in users:
        print(user)

userdetails("Suresh", "Rohini", "Trishika", "Hanshith")

If you observe the above example, we added an asterisk (*) symbol before the parameter name in the function definition to handle any number of parameters.

 

When you execute the above python program, you will get the result as shown below.

 

Suresh
Rohini
Trishika
Hanshith

Return Statement in Function

You can use the return statement in function to return the values. Following is the example of creating a function to return a value in python.

 

def multiply(a, b):
    return a * b
c = multiply(10, 5)
print("10 * 5 = {}".format(c))

The above example will return the result as shown below.

 

10 * 5 = 50

This is how you can use python functions to execute a block of statements whenever it is called in applications.