Functions in Python

Functions are units which perform a particular task, take some input, and which may give some output. Functions form the basis of procedural programming. One advantage is the division of a program into smaller parts.

Features of Functions

Modular Programming: If a program is divided into small parts in such a way that different parts each perform some specific task, then each part can be called as per the requirement.

Re-usability of Code: A function can be called many times. This can reduce the length of the program.

Manageability: Dividing a bigger task into smaller functions makes the program manageable. It becomes easy to locate bugs and therefore make the program reliable.

Basic Terminology 

Name of a Function

A function can have any legal literal name. For example, sum1 is a valid function name as it satisfies all the requisite constraints. The name of a function should be meaningful and, if possible, convey the task to be performed by the function.

Arguments

The arguments of a function denote the input given to a function. A function can have any number of arguments or it is possible that a function may not have any argument. The list of parameters (separated by commas) is given in the parentheses following the name of the function.

In Python, while defining a function the types of arguments are not specified. This has the advantage of giving different types of arguments in the same function.

Body of the function

The body of the function contains the code that implements the task to be performed by the function.

Return Value

A function may or may not return a value.

How to Define Function

The task to be performed by the function is contained in the definition.

Example: Function which multiplies two numbers passed as parameters.

def product(num1, num2):
    p = num1 * num2
    return p

The name of this function is product. It takes two arguments as input (num1 and num2), calculates the product and returns its value.

How to Invoke Function

The invocation of a function can be at any place after the definition. A function can be called any number of times.

result = product(5, 3)
print(result)