Section5 1-2+notes+
Section5 1-2+notes+
1 Notes
The process of splitting a large task into manageable small tasks is called divide-and-conquer. This
process is what facilitates program modularization.
A modularized program is one that is written as a collection of functions. The concept of program
modularization is important in programming for the following reasons.
There are two types of functions: void and value-returning functions. A void function executes
statements in the function and terminates, whereas, a value-returning function executes statements in
the function and returns value to the caller (another function or part of the program that calls it).
The print function is an example of a void function. Although, it displays a string to the screen, it does
not return value to the caller.
The float, input and int functions are examples of a value-returning function.
The code for a function is called function definition. Like a variable, a function must have a name that is
used to reference it in the computer memory. The function name follows the same naming convention
used in a variable, namely,
As a good programming style, it is advisable to use verbs as function names to describe the actions of
the function.
A function definition causes the function to be loaded to the memory, it does not cause it to execute. A
function MUST be called in a program to execute it.
function_name()
For example, define a function that will prompt the user to enter an integer, the function will display
whether the integer entered is divisible by 5.
1. #function definition
2. def is_divisible_by_5(): #function header
3. n = int(input('Enter an integer')) #prompt user to enter an integer
4. if n % 5 ==0: #check if divisible by
5. print(n, 'is divisble by 5')
6. else:
7. print(n, 'is not divisible by 5')
8. #function call
9. is_divisible_by_5()
Here, the function name is is_divisible_by_5 (see line 2, the function header). The function call (also
known as function invocation) is in line 9. Lines 2-7 form the function definition and at this point of the
program, the function is loaded to the memory. When line 9 is executed, the program flow goes to the
function loaded in the memory and execute it by executing all statements in the function.
The statements in the function are consistently indented; this is important because, it tells the Python
interpreter where the block start and end.