Computer Science · Ch 7 — Functions
Introduction
Introduction
As programs grow to solve bigger problems, the number of lines of code grows with them. A long, single-block program quickly becomes bulky, hard to read and hard to maintain — spotting an error or changing one calculation means wading through the whole file. This chapter introduces the way programmers tame that growth: breaking a program into smaller, named, independent pieces.
A real-world problem: pricing a tent
Consider a company that manufactures tents to each customer's requirements. The tent's shape is a cylinder surmounted by a conical top (see Figure 7.1). To fix the selling price of a tent, the company must:
- Accept the user's requirements for the tent — a) height of the cylindrical part, b) radius, and c) slant height of the conical part.
- Calculate the area of the canvas needed to make the tent.
- Calculate the cost of that canvas.
- Calculate the net amount payable by the customer, which includes 18% tax.
The whole computation can be written as one straight-line program:
# Payable amount for the tent, written WITHOUT functions
print("Enter the dimensions of the cylindrical part in metres")
h = float(input("Height of the cylindrical part: "))
r = float(input("Radius: "))
l = float(input("Slant height of the conical part in metres: "))
area_cone = 3.14 * r * l # curved surface area of the conical top
area_cylinder = 2 * 3.14 * r * h # curved surface area of the cylindrical body
# total canvas used to make the tent
canvas = area_cone + area_cylinder
print("Canvas required:", canvas, "sq. m")
# cost of the canvas
rate = float(input("Cost of 1 sq. m of canvas: "))
cost = rate * canvas
print("Total cost of canvas:", cost)
# add 18% tax to get the net payable amount
tax = 0.18 * cost
payable = cost + tax
print("Net amount payable:", payable)
This works, but everything — input, three different calculations, tax — sits in one undifferentiated block. If the company later changes how one part is computed, the programmer must hunt through the entire listing.
The alternative: divide the program into blocks
Another approach is to split the same program into separate blocks of code, each with its own name and its own specific job (see Figure 7.2). For the tent problem the natural blocks are:
- a block
cyl(h,r)that calculates the curved surface area of the cylindrical part, - a block
con(l,r)that calculates the curved surface area of the conical part, and - a block
post_tax_price(cost)that calculates the tax and the net price.
The main program then simply calls these blocks in order, instead of containing all their code inline.
Modular programming
The process of dividing a computer program into separate, independent blocks of code — separate sub-problems, each with a different name and a specific functionality — is called modular programming. Each block solves one sub-problem; together they solve the whole problem.
The rest of this chapter explores the benefits of this approach: what functions are and why they help (Section 7.2), how to create our own user defined functions with parameters and return values (Section 7.3), how the scope of a variable works (Section 7.4), and the ready-made functions and modules that Python's standard library provides (Section 7.5).
Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your textbook's own diagram.
Figure 7.1 shows the shape of the tent at the heart of this chapter's opening problem: a solid blue three-dimensional silhouette in which a vertical cylinder forms the body and a wider cone sits on top as the roof. Where the conical top overhangs the cylindrical body, an elliptical rim is visible, and the tent stands on an elliptical base. No labels or dimensions are marked on the figure — it exists purely to fix the geometry in your mind.
That geometry is exactly what the pricing program has to handle: the canvas of the tent is the curved surface of the cylindrical part plus the curved surface of the conical top. This is why the program asks the user for three measurements — the height of the cylindrical part, the radius, and the slant height of the conical part — and why the computation naturally splits into separate blocks (one for the cylinder's area, one for the cone's area), motivating the idea of modular programming that the chapter develops.
Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your textbook's own diagram.
Figure 7.2 pictures the key move of this chapter: taking the one-block tent-pricing program and dividing it into separate named blocks of code — modular programming.
On the left sits a small blue tent shape (the cylinder-with-conical-top from Figure 7.1), representing the problem to be solved. From it, three arrows point rightward to three stacked rectangular boxes, each describing one block of the program:
- Block name:
cyl(h,r)— calculates the curved surface area of the cylindrical part. - Block name:
con(l)— calculates the curved surface area of the conical part. - Block name:
post_tax_price()— calculates the tax and the net price.
The message of the diagram is that one bulky program can be decomposed into independent sub-problems, each with its own name and its own specific functionality. Each box corresponds directly to a user defined function in the rewritten program of Section 7.2: the main program simply calls cyl(), con() and post_tax_price() in turn instead of containing all of their code inline. The arrows fanning out from the single tent emphasise that the three blocks together solve the one original problem.