2.2.8 Subprograms
In this lesson, you will learn how subprograms are used to break programs into smaller, reusable sections of code. You will explore procedures and functions, learn how parameters and arguments pass data into subprograms, understand how arrays can be processed by them, and examine the difference between local and global scope.
Subprograms
As programs become larger, placing every instruction in one continuous block makes the code difficult to understand, test and maintain. A subprogram (or sometimes called a subroutine) is a named section of code designed to perform a particular task. The main program can call the subprogram whenever that task is required.
When a subprogram is called, control moves from the main program into the subprogram. Its instructions are executed, and when it finishes, control returns to the point in the main program from which it was called.
Subprograms make programs easier to structure because they allow a large problem to be decomposed into smaller tasks. They can also reduce repeated code, make testing and debugging easier, and allow useful code to be reused. There are two main types of subprogram: procedures and functions.
Procedures
A procedure is a named subprogram that performs a task but does not return a value to the part of the program that called it.
A procedure must first be defined. Once defined, its identifier can be used to call it whenever the task is needed.
procedure displayWelcome()
print("Welcome to the revision quiz")
endprocedure
displayWelcome()In Code 1 above, the section between and defines what does. The final instruction, , is the procedure call. When this call is reached, control moves into the procedure, the message "Welcome to the revision quiz" is printed, and control returns to the main program.
Python does not have a separate keyword. Instead, Python uses to define subprograms. A Python subprogram that performs an action without returning a useful value can therefore be used in the same way as a procedure as shown in Code 2 below.
def display_welcome():
print("Welcome to the revision quiz")
display_welcome()As in the OCR ERL version, is first defined and is then called from the main program. When the call is made, the instructions inside the subprogram execute before control returns to the main program.
The procedure in Code 1 always performs exactly the same task because no data is passed into it. A subprogram becomes more flexible when data can be passed into it, allowing the same subprogram to work with different values each time it is called.
A parameter is a variable named in a subprogram’s definition that receives a value when the subprogram is called. An argument is the actual value supplied in the call. Consider the following example in Code 3 below.
procedure displayPrice(item, price)
print(item, " costs £", price)
endprocedure
displayPrice("Notebook", 3.50)
displayPrice("Pen", 1.20)The procedure defines two parameters: and . In the first call , "Notebook" and 3.50 are the arguments passed into those parameters. In the second call , different arguments are supplied.
The same procedure can therefore perform the same general task using different data without the code having to be rewritten, as shown in Code 4 below.
def display_price(item, price):
print(item, "costs £", price)
display_price("Notebook", 3.50)
display_price("Pen", 1.20)The same distinction applies in Python: and are the parameters defined by the subprogram, while "Notebook" and 3.50 are the arguments supplied when it is called.
Functions
A function is a subprogram that performs a task and returns a value to the part of the program that called it. This returned value can then be assigned to a variable, displayed, or used in another calculation.
function calculateDiscount(price)
discountedPrice = price * 0.9
return discountedPrice
endfunction
finalPrice = calculateDiscount(50)
print(finalPrice)In Code 5 above, is defined as a function with one parameter, . When is called, the argument 50 is passed into . The function multiplies this value by 0.9, producing 45, which is stored in the local variable .
The statement then sends this value back to the part of the program that called the function. As a result, the returned value 45 is assigned to , which is then output by .
This demonstrates the key difference between a function and a procedure: a procedure carries out its instructions and then returns control to the calling program, whereas a function also returns a value that the calling program can use.
Python uses to define both function-like and procedure-like subprograms. A Python subprogram that returns a value uses a statement, as shown in Code 6 below.
def calculate_discount(price):
discounted_price = price * 0.9
return discounted_price
final_price = calculate_discount(50)
print(final_price)Code 6 follows the same process as the OCR ERL function. The argument 50 is passed into , the discounted value is calculated, and sends the result back to the function call. In Python, produces the floating-point value 45.0, so this value is assigned to and then output. The .0 indicates that Python is representing the result as a floating-point number rather than an integer.
Earlier, we saw how individual values such as "Notebook" and 3.50 can be passed into a subprogram as arguments. An entire array can also be passed as an argument, allowing a function or procedure to process a collection of related values without each element having to be supplied separately.
Suppose the array contains four temperature readings. In Code 7 below, the entire array is passed to the function.
function findTotal(values)
total = 0
for index = 0 to values.length - 1
total = total + values[index]
next index
return total
endfunction
temperatures = [12, 15, 14, 11]
print(findTotal(temperatures))When is called, the array is passed into the parameter . Inside the function, the FOR loop uses to access each element in turn and adds it to . Once every element has been processed, the function returns the final .
The function therefore works with the complete array through a single parameter rather than requiring each temperature to be passed separately. Python can perform the same task by passing a list to a function, as shown in Code 8 below.
def find_total(values):
total = 0
for value in values:
total = total + value
return total
temperatures = [12, 15, 14, 11]
print(find_total(temperatures))Arrays or lists can therefore be processed by reusable subprograms in the same way as individual values.
An important advantage of subprograms is that they reduce duplicated code. Without a subprogram, the same calculation may need to be written separately every time it is required. For example, the following Python code in Code 9 calculates the areas of three rectangles.
print(5 * 3)
print(8 * 4)
print(10 * 6)Although the values are different, the same calculation, , has been repeated three times. If the way the area were calculated needed to change, each copy of the calculation would also need to be changed. Repeating the same logic in multiple places also makes programs longer and harder to maintain. Instead, the calculation can be defined once in a function and reused, as shown in Code 10 below.
def rectangle_area(length, width):
return length * width
print(rectangle_area(5, 3))
print(rectangle_area(8, 4))
print(rectangle_area(10, 6))The calculation is now defined in one place. Each function call supplies different arguments, but the same function performs the calculation. This reduces duplicated code and makes the program easier to read, test, maintain, and modify.
Local and Global Variables/Constants
Variables and constants also have a scope. Scope determines which parts of a program can access and use a particular identifier. An identifier does not necessarily exist everywhere in a program simply because it has been created somewhere within the code.
The two main types of scope are local and global scope. A local variable or constant belongs to a particular subprogram, whereas a global variable or constant is defined outside individual subprograms and is available more widely within the program.
Local Variables/Constants
A local variable or constant is created inside a subprogram and can normally be accessed from within that subprogram. It can be used by instructions within that subprogram, but code elsewhere in the program cannot directly access it.
Consider the Python function in Code 11 below, which calculates the total cost of several identical items.
def calculate_total(price, quantity):
total = price * quantity
return totalWhen the function is called, is created inside and stores the result of . Because is defined within the function, it has local scope: it can be used by instructions inside , but code outside the function cannot normally access it directly.
The parameters and are also local to the function. Their values are available while the function is executing but are not identifiers that the rest of the program can directly use.
Local scope allows different subprograms to have their own temporary data without unnecessarily exposing or interfering with values elsewhere in the program.
Global Variables/Constants
A global variable or constant is defined outside individual subprograms and has a wider scope. This allows the same value to be accessed by different parts of the program rather than belonging to only one subprogram.
For example, suppose a program keeps a count of the total number of visits. Because this value needs to exist beyond a single call to , it can be stored in a global variable, as shown in Code 12 below.
visits = 0
def record_visit():
global visits
visits = visits + 1
record_visit()
print(visits)The variable is created outside , so it has global scope. Its initial value is 0. Because needs to modify this global variable, the statement is included inside the function.
In Python, the keyword tells the function that refers to the existing global variable defined outside the function. Without this declaration, assigning a value to inside the function would cause Python to treat it as a local variable instead.
When is called, the statement tells Python that the function should use and modify the existing global variable rather than treat as a separate and new local variable that needs to be created. The instruction therefore reads its current value of 0, adds 1, and assigns the new value 1 back to the same global variable.
When control returns to the main program, the changed value still exists, so outputs 1.
Global variables can therefore be useful when several parts of a program genuinely need to share the same value. However, they should not be used unnecessarily. If many subprograms can change the same global variable, it becomes harder to determine where and why its value has changed.
