Edexcel International Advanced Level Computer Science, point 10.2.1
In Unit 2 you are often given an algorithm and asked to convert it into code. It may be expressed in words, in a diagram, or in a flowchart (5.1.1). The skill is to follow the logic exactly and translate each step into correct Python.
A method
- Read the whole algorithm first, and work out what it does.
- Identify the inputs, outputs and any stored values (variables).
- Find the structure: sequence, selection (decisions) and iteration (loops).
- Translate each part, in order, into code.
- Match the names and conditions in the algorithm.
- Test with a trace table or sample data (5.1.2), and check boundary cases.
| Algorithm feature | Python |
|---|---|
| "Set X to 0" / "X = X + 1" | x = 0 / x = x + 1 |
| "Ask the user for..." | input() (convert the type) |
| "Output..." | print() |
| "If ... otherwise ..." / a diamond | if / else |
| "Repeat N times" | for ... in range(N) |
| "Repeat while ..." / "until ..." | while ...: ("until C" is "while not C") |
| "For each item in ..." | for item in items: |
| A subprocess box | A call to a subprogram |
a. An algorithm expressed in words
- Set total to 0.
- Set count to 0.
- Ask the user for a number.
- While the number is not −1:
- add the number to total
- add 1 to count
- ask the user for the next number.
- If count is more than 0, output total divided by count. Otherwise, output "No numbers".
Code:
total = 0 # 1
count = 0 # 2
number = float(input("Number: ")) # 3
while number != -1: # 4
total = total + number
count = count + 1
number = float(input("Number: "))
if count > 0: # 5
print(total / count)
else:
print("No numbers")
Each numbered step maps to code. The "ask for the next number" step inside the loop is what stops it being infinite.
b. An algorithm expressed in a diagram
A diagram may show steps in boxes with arrows, or a structure such as a hierarchy chart (10.1.2), or a diagram of how data changes. An entity-relationship diagram (4.1.1) is a diagram too: each entity becomes a CREATE TABLE statement, with its keys, as in 8.3.1.
Example: a hierarchy chart with a main program calling three subprograms
Code (each box becomes a subprogram; the top box calls the others):
def read_order():
qty = int(input("Quantity: "))
price = float(input("Price each: "))
return qty, price
def calculate_total(qty, price):
return qty * price
def print_receipt(total):
print(f"Total: £{total:.2f}")
def process_order():
qty, price = read_order()
total = calculate_total(qty, price)
print_receipt(total)
process_order()
A decision table
A decision table lists every combination of conditions and the result for each. Each row becomes one path through if statements.
| Age | Weekend? | Price (£) |
|---|---|---|
| under 16 | No | 4.50 |
| under 16 | Yes | 6.00 |
| 16 or over | No | 8.00 |
| 16 or over | Yes | 10.00 |
Code:
def ticket_price(age, weekend):
if age < 16:
if weekend:
return 6.00
return 4.50
if weekend:
return 10.00
return 8.00
Testing: use one test for each row of the table, with at least one on the boundary (age 15 and 16): ticket_price(15, False) gives 4.50, ticket_price(15, True) 6.00, ticket_price(16, False) 8.00 and ticket_price(16, True) 10.00.
c. An algorithm expressed in a flowchart
Use the symbols (Appendix 2): terminators, input/output parallelograms, process rectangles, decision diamonds and arrows.
Translating a flowchart:
- A decision whose "yes" arrow leads back round is a loop (
while). - A decision with two separate paths is
if/else. - Process boxes are assignment statements.
- Parallelograms are
inputandprint.
Code:
n = int(input("n: "))
fact = 1
i = 1
while i <= n:
fact = fact * i
i = i + 1
print(fact)
Test: n = 4: fact goes 1, 1, 2, 6, 24, so the output is 24 (4!).
Converting "until" and other tricky forms
An algorithm may use a "repeat ... until" loop, which always runs at least once and stops when the condition is true. Python has no such loop, so use while True with break:
# Repeat: ask for a password. Until it equals "secret"
while True:
attempt = input("Password: ")
if attempt == "secret":
break
Common mistakes
- Wrong boundary (
<instead of<=). - Forgetting to update the loop variable, causing an infinite loop.
- Forgetting to convert
input()to a number. - Mis-ordering steps (using a variable before setting it).
- Not matching the algorithm's names or output wording.
- Putting the output inside the loop when it belongs after.
Worked example
Task: convert this flowchart-style algorithm (given in words) into code: "Set largest to the first item of the list. For each of the remaining items, if the item is greater than largest, set largest to that item. At the end, output largest."
numbers = [14, 3, 27, 9, 21]
largest = numbers[0] # set largest to the first item
for item in numbers[1:]: # each of the remaining items
if item > largest: # decision
largest = item # process
print(largest) # output after the loop: 27
Check with a trace: largest goes 14, 14 (3 isn't greater), 27, 27, 27, and 27 is output. A test with all negative numbers ([-5, -2, -9]) gives -2, so the initial value is right.
Exam tip: follow the algorithm exactly, using its order, conditions and output wording. Decide the loop type from the wording ("repeat N times" is for, "while" is while). Test your code with the sample data the question gives, and compare with the expected output.
Check yourself
How do you convert "repeat ... until the password is correct" into Python?
Use while True with the input inside, and break when the password is correct (or while not correct).
In a flowchart, what does a decision whose "yes" path returns to an earlier step represent?
A loop, such as a while loop.
What must you remember about input() when an algorithm needs a number?
It returns a string, so convert it with int() or float().
Why test converted code with the sample data?
To check it gives the expected output, which shows the algorithm was translated correctly.