Introduction to Python : Functions

Functions

A function is a callable block of code. Callable implies that, the block of code can summoned (called) in different parts of the program to execute a particular task. Functions are very important in any programming language since it allows the grouping of certain tasks that may be needed in different parts of the program without duplicating the same code. Let us illustrate this with a simple example:

def printer(value1, value2):
   print ("I have to print", value1, value2)

x = 5
y = 10

printer(x, y)

k = "Python"
j = "is cool"

printer(k, j)

Output:

I have to print 5 10

I have to print Python is cool

As seen from the outputs, the 'printer' function which accepts two values 'value1' and 'value2' was defined once in the program but called two times with different values. In both cases, the task accomplished was the same (print some a string and two values) even though the values were different in the function calls.

A function may also return a value or the result of an evaluation. Example:

def modulo_calc(x, y):
   z = x % y
   return z

m = 5
n = 2

k = modulo_calc(5, 2)
print("The result of 5 modulo 2 is", k)

This program defines a function (modulo_calc) which calculates the modulo of a two numbers and return the result. It then calls the function and passes two values to it and the prints the result returned by the function which is 1. The out put of the program is therefore:

The result of 5 modulo 2 is 1


course logo
Introduction to Python
Number of sections:
11
Content length:
Delivery formats: