Python Programming – Python User Defined Functions

As we have seen in the previous section that Python contains a rich set of built-in functions. However, the programmer can develop their own functions depending upon their requirement and such functions are termed user-defined functions. In formal language, functions that are defined by us to perform certain specific operations or tasks are termed as user-defined functions.

Formally, the user-defined functions contain two parts:

  • Function Definition: contains the actual code for the operation to be performed.
  • Function Call: where the call to the function definition is made to perform a specific operation.

Function Definition (Defining a Function in Python)

Unlike C/C++/Java, the format of Python user-defined functions is different. The syntax of user-defined functions is given below:

def function_name(list of parameters):
“docstring”
statement(s)
return(parameter)

The above syntax of function definition has the following components:
1. The keyword def symbolizes the start of the function header.

2. A function name to uniquely identify it. Function naming follows similar rules that are used for writing identifiers as described in Chapter 2.

3. List of parameters also called a list of arguments through which value is passed to the function. The list of parameters is optional.

4. A colon (:) to mark the end of function header.

5. Optional documentation string (docstring) is used to describe the purpose of the function, which is slightly similar to python documentation using comment.

6. Python statements that perform the intended task for which the user-defined function is made. It is mandatory to maintain the indentation level while writing python statements in the function definition.

7. At the end an optional return statement is used to return a value (result) from the function. This statement can contain an optional parameter to return the computed result back to the function call. If there is no parameter in the statement or the return statement is not mentioned at the end of the function definition then the function returns the None object.

Function Call

The function definition described above provides the code that is intended to perform a certain operation based on parameters given and statements written. Once the function definition is finalized, the programmer can call it from another function or from the Python prompt. This can be done by just writing the function name and specifying the list of parameters (if desired). Consider the following program Code 6.1. which, prints a message using Python user
defined function.

Code: 6.1. Illustration of Python user-defined function.

# This program illustrates the Python user defined function

#function definition of print_msg( )
def print_msg(str):
“This function prints the value of str passed as a parameter”
print(str)
return

# function call of print_msg()
print_msg(“print_msg is a user-defined function.”)
print_msg(“another call to print_msg function.”)
print_msg(“Hello, Welcome to Python Programming!”)

Output

print_msg is a user-defined function.
another call to print msg function.
Hello, Welcome to Python Programming!

Types of Function Arguments (Parameters)

In Python user-defined functions can be used with different types of argument lists. The types are given as follows:

  1. Functions with no arguments
  2. Functions with required arguments
  3. Functions with variable arguments
  4. Functions with keyword-based arguments
  5. Functions with default arguments

Functions with No Arguments

Alike,’ C and C++, Python user-defined functions can be defined without specifying an argument list. Such functions perform the intended task on their own without fetching any data from the function call. The programming code representing function with no argument is displayed in Code 6.2. In the program, we see that the function print msg() prints the message without fetching it as an argument from the function call. Another example to compute the sum of two _ numbers without any argument passing is given in Code 6.3. We can see that the program very effectively produces the output and displays the result as desired.

Code: 6.2. Illustration of function with no argument list.

# This program illustrates the Python user-defined function with no argument list

def print_msg():
“This function prints the message” print(‘Hello, Welcome to Python Programming!’)
return

# function call of print_msg()
print_msg()

Output

Hello, Welcome to Python Programming!

Code: 6.3. Illustration of function to compute sum of two numbers without argument list.

# This program illustrates the Python user defined function with no argument list

def sum( ):
“This function computes sum of two numbers”
a=10
b=20
. print(‘sum={0}’.format(a+b))
return

# function call of print_msg()
sum()

Output

Sum=30

Functions with Required Arguments

While making a function call, a list of arguments is supplied, which is fetched by the function definition. The arguments passed must be incorrect positional order and must match exactly with that of the function definition. The program signifying the use of required arguments is given in Code: 6.4. The program computes the sum of two numbers by using functions with required arguments. We see that two values 10 and 20 are passed as arguments to function sum(), which then produces the intended output. Another example of the same program with using return statements is given in Code 6.5. We see that the computed result is sent back to the calling function by the return statement and the result is displayed after the function call and not in the function definition.

Code: 6.4. Illustration of function to compute sum of two numbers with required argument list.

# This program illustrates the Python user defined function with argument list

def sum(a, b):
“This function computes sum of two numbers”
print(‘sum= {0} \format(a+b))
return

# function call of print_msg()
sum(10, 20)

Output

Sum=30

If the user does not supply the argument value, where the argument is desired then the Python interpreter generates an error message. This is illustrated in Code: 6.6. and the output is given in Fig. 6.1.

Code: 6.6. Illustration of not specifying required argument list.

# This program illustrates the Python user defined function with no required argument list

def sum(a, b):
“This function computes sum of two numbers”
print(‘sum= {0 }’. format(a+b))
return

# function call of print_msg()
sum( )

Python Programming - Python User Defined Functions chapter 6 img 1

Functions with Arbitrary Length Arguments

In the above, we have discussed functions without a list of arguments and with a list of required arguments. The Python language has the feature of variable length arguments in which the programmer can specify any number of arguments depending upon the requirement. The syntax of arbitrary length arguments is as under:

def function name(*var args tuple):
“function documentation using Docstring”
statement(s)
return(expression)

An asterisk (*) preceding the variable name is intended to hold the values of all nonkeyword arbitrary arguments. This tuple remains empty if no additional arguments are specified during the function call. The programming code illustrating the concept of variable length arguments is given in Code: 6.7. In this program, a variable list is passed as an argument to the var_func() with values from 10, 20, …, 100. The concept of arbitrary length arguments is used for passing tuple or lists as arguments. It is similar to passing array elements to a function in C. However, in Python, the method to perform the same is rather simple.

Code: 6.7. Illustration of variable length arguments passed to a user-defined function.

#This program illustrates the python user-defined function with arbitrary length arguments

def var_func(*list):
“This function prints variable passed as arguments” for i in list:
print(i)
return

# function call of print_msg ( )
var_func(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)

Output:

10
20
30
40
50
60
70
80
90
100

Functions with Keyword Based Arguments

In keyword-based arguments, a value is assigned to the argument in the function call. While passing keyword-based arguments, the caller identifies the arguments by parameter name. By using this feature, the programmer can place arguments out of order. As it is the responsibility of the interpreter to use the keywords to match the values with parameters. The programming in Code 6.8. represents the concept of keyword-based arguments. It is apparent from the output that in the function call the argument Name is passed first and empty is passed at second place. However, the function definition receives the parameter values based on the keywords supplied rather than the order in which they are passed.

Code: 6.8. Illustration of variable length arguments passed to a user defined function.

# This program illustrates the Python user defined function with keyword based arguments

def employee_info(empID, Name):
print(empID)
print(Name)
return

# function call of print_msg()
employee_info(Name=”John”, empID=1234)

Output:
1234
John

Functions with Default Arguments

A default argument is used to set the default value of an argument for which a value is not passed by the function call. Then that default value is fetched by the function definition for further computations. The program representing the concept of default value argument is given in Code 6.9. It can be seen that in the first call to function employee_info(), all the arguments are passed with a value. However, in the second call to employee_info(), only the value of argument empty is passed, and the rest two default values of Name and salary are taken up by the function definition.

Code: 6.9. Illustration of default arguments passed to a user defined function.

#This program illustrates the python user defined function with default arguments

def employee_info(empID, Name=’John’, salary=8000):
print(empID)
print(Name) print(salary)
return

# function call of print_msg()
employee_info(Name=”Harry”, empID=llll, salary= 10000)
employee_info(empID=2222)

Output:

1111
Harry
10000
2222
John
8000

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *