Writing and Refining Algorithms
Completing an algorithm means filling the missing lines, or missing parts of lines, in an algorithm that is partly written. The description of the problem tells you what each gap must do, so read it closely before you write anything.
Use the description to work out the job of each gap. A gap might need an input, a condition, a calculation, a counter update or an output. For example, a print shop charges 6p per page. Orders of 100 pages or more are charged at 5p per page. The condition gap must test the variable pages and must include 100, so the completed line uses the greater-than-or-equal-to operator. The calculation gap must work out the cost using the lower rate, and the output gap must print the final cost. A gap that is only part of a line might be just the operator or the variable name, so choose that part from the wording of the description.
The completed line must keep the style of the surrounding lines. Use the same keywords, the same variable names and the same indentation. If the surrounding code uses if and indents the branch by four spaces, your line does the same. Do not add steps the description did not ask for, and do not rewrite lines that are already correct.
After all the gaps are filled, test the finished algorithm with values. Include boundary values — the values at the edge of a condition — because they show whether the condition includes or excludes the right value. For the print shop rule, test 99, 100 and 120. Check that 100 gets the lower rate, 99 does not, and 120 is also charged at the lower rate.
pages = int(input("Enter number of pages: "))
cost = pages * 0.06
if pages >= 100:
cost = pages * 0.05
print("Final cost:", cost)Output when the user types 100:
Enter number of pages: 100
Final cost: 5.0 OCR GCSE Computer Science · Writing and Refining Algorithms
OCR GCSE Computer Science · Selection