Completing programs
How these questions work
On an onscreen paper you are not given an empty page. You are given a program that is partly written, and the question tells you what to do to it: complete it, amend it, fix it or extend it. The questions here work the same way.
- The editor opens on the partly written program. Change only what the task asks for.
- Your program runs against tests, shown with the question. A call test checks what one function returns; an input test types lines into your program and checks exactly what it prints.
- Your mark is your share of the tests passed, so a program that does part of the job earns part of the marks.
The program in the editor is the question. Read all of it before you type anything.
Read before you write
A partly written program tells you a lot: which variables already exist, what each subroutine is called, and what the comments ask for. Read it in this order:
- Read the task, then the tests: they show the names, the inputs and the exact outputs wanted.
- Read the program from the top. Note every variable that is set up and every subroutine that is defined.
- Find each comment that marks a gap, such as # Complete this line.
- Work out one test by hand, so you know what the finished program should give.
- Fill one gap at a time and run the tests after each.
def mean_score(scores):
total = 0
for s in scores:
total = total + s
# Return the mean, rounded to 1 decimal place
Here the loop has already made total. The missing line divides it by how many scores there are and rounds the result: len(scores) gives the count, and round(value, 1) rounds to 1 decimal place.
Subroutines, parameters and return values
A subroutine is a named block of code. A function returns a value with return; a procedure does a job, such as printing, and returns nothing. Parameters are the names in brackets on the def line; the values passed in when it is called are the arguments.
To make a subroutine more useful, a fixed value inside it can become a parameter:
def add_tax(price):
return round(price * 1.2, 2) # always 20%
def add_tax(price, rate):
return round(price * (1 + rate / 100), 2)
Now the caller chooses the rate: add_tax(50, 5) returns 52.5. Keep the name the question gives, and put the new parameter where the question says.
Main programs and libraries
The main program is the code outside the subroutines. It reads the input, calls the subroutines with the right arguments and prints what they return. When you complete a main program, use the subroutines you are given rather than copying their code.
Python's libraries add ready-made subroutines. Write import math at the top of the program, then use:
math.ceil(x)to round up, such as the number of boxes needed when a part-full box still counts;math.sqrt(x)for a square root;math.pifor pi.
round(), len(), int(), str() and format() are built in and need no import.