Selection chooses which code to run, depending on whether a condition is True or False.
The code that belongs to an if, elif or else is the indented block under it. The line after the block runs whatever happened.
For ranges, test in order from one end: start at the top with >, or at the bottom with <. In the wrong order, a value can fall into the wrong band.
One if … elif … else is better than several separate ifs. It stops testing once one condition is True, and only one block can run.
You can nest selection (an if inside another), but elif is usually clearer.
Use
When
if
Something happens only when the condition is True
if … else
One thing when True, a different thing when False
if … elif … else
Several conditions, tested in order. The first True one runs and the rest are skipped. else catches everything left
Worked exampleA weather app labels wind speeds in km/h. What does this program output for 38, and why would swapping the second and third tests be a mistake?
38 < 40 is True: output Breezy, skip the restonly the first True branch runs
If the < 62 test came before < 40, then 38 < 62 would be True first38 would be labelled Gale
Breezy. The tests must go in order (20, 40, 62) so each value lands in the right band.
Exam tipWatch the indentation of a print after an if. Indented, it only runs when the condition is True. Not indented, it always runs. Examiners saw programs announce a result even after invalid input because of this.
Selection
Choosing which statements to run depending on a condition.
Nested selection
An if statement inside another if statement.
Edexcel 1CP2 · 6.2.2
Count-controlled loops: for … in range ()
A count-controlled loop repeats a set number of times, known before the loop starts.
range (start, stop, step) counts from start up to but not including stop, adding step each time.
To include a last value, make stop one more than it: 1 to 10 is range (1, 11).
Counting down needs a negative step, and stop one below the last value: 5 down to 1 is range (5, 0, -1).
The loop variable can be used inside the loop. Don’t change it yourself.
Code
Values of n
for n in range (4):
0, 1, 2, 3 (start defaults to 0)
for n in range (1, 6):
1, 2, 3, 4, 5
for n in range (2, 11, 3):
2, 5, 8
for n in range (10, 0, -2):
10, 8, 6, 4, 2 (counting down)
for n in range (5, 5):
none: the loop body never runs
The stop value is never included
Worked exampleWrite a loop that shows the 7 times table from 7 × 1 to 7 × 12, one line each.
for times in range (1, 13):13 so that 12 is included
print ("7 x " + str (times) + " = " + str (7 * times))convert numbers before joining
for times in range (1, 13):
print ("7 x " + str (times) + " = " + str (7 * times))
Exam tipOff-by-one errors in range are a favourite ‘fix the errors’ logic error. Write out the first and last values the loop really gives.
Repetition
Going round a loop running the same instructions while a condition is True (or a set number of times).
Count-controlled loop
A loop whose number of passes is known before it starts, e.g. for … in range ().
Edexcel 1CP2 · 6.2.2
Condition-controlled loops: while
A condition-controlled loop repeats while a condition is True. The number of passes isn’t known when it starts.
while (condition): tests the condition before each pass. If it is False the first time, the body never runs.
Something inside the loop must eventually make the condition False, or the loop never ends (an infinite loop).
A sentinel value is a special input that means ‘stop’, such as an empty string, 0 or −1. Pick one that can’t be real data.
Pattern for input loops: take the first input before the loop, and the next input as the last line inside the loop.
A Boolean flag such as finished = False can control a loop: the loop sets it to True when it should stop. This gives the loop one exit. Pearson’s guidance is to avoid break.
Worked exampleWrite a program that adds up the donations counted from a charity collection until 0 is entered, then shows the number of donations and the total.
Read the first donation before the loopso the condition has a value to test
while (donation != 0):0 is the sentinel
Add to the total, count the donation, then read the next one as the last line of the loopthe new donation is tested next time round
total = 0.0
donations = 0
donation = float (input ("Donation (0 to finish): "))
while (donation != 0):
total = total + donation
donations = donations + 1
donation = float (input ("Donation (0 to finish): "))
print ("Donations:", donations)
print ("Total: £" + "{:.2f}".format (total))
Exam tipA loop that never ends is a logic error. Check the loop changes the variable in its condition: a new input, a counter going up, or a flag being set.
Condition-controlled loop
A loop that repeats while a condition is True; the number of passes isn’t known in advance.
Sentinel value
A special value, such as −1 or an empty string, that tells a loop to stop.
Infinite loop
A loop whose condition never becomes False, so it never stops.
Flag
A Boolean variable that records whether something has happened, e.g. found = True.
Edexcel 1CP2 · 6.2.2
Iteration: going through every item
Pearson uses iteration for a loop that processes every item in a data structure, such as a list or a string.
Use for item in list: when you just need each value.
Use for index in range (len (list)): when you need the position too: to change an item, to report where it is, or to use the same index in another list.
Use a while loop with an index when the loop may need to stop early (see linear search).
Pearson says not to worry about fine distinctions. If a task says ‘iteration’, a for loop over the structure is expected.
Loop
What it gives you
Pearson calls it
for item in scores:
Each item in turn
Iteration
for index in range (len (scores)):
Each position 0, 1, 2… so you can use scores[index]
Iteration (the numbers index the list)
for count in range (5):
The numbers 0 to 4, used only to count passes
Repetition (count-controlled)
while (answer != "N"):
Passes until the condition is False
Repetition (condition-controlled)
Worked examplepulseRates = [72, 65, 80, 77]. Show two ways to output every pulse rate, and a loop that adds 2 to every item in the list itself.
for rate in pulseRates: then print (rate)each value in turn
for index in range (len (pulseRates)): then print (pulseRates[index])the index picks each item
pulseRates[index] = pulseRates[index] + 2 inside the index loopchanging an item needs its position
pulseRates = [72, 65, 80, 77]
for rate in pulseRates:
print (rate)
for index in range (len (pulseRates)):
pulseRates[index] = pulseRates[index] + 2
print (pulseRates)
Exam tipIn a ‘name the part’ question, don’t give a repetition line where iteration is asked for, or the other way round. Examiners mark them as different answers.
Iteration
Going round a loop until every item in a data structure has been processed.
Edexcel 1CP2 · 6.3.1
Lists as arrays
An array is a sequence of items of the same data type. In Python an array is a list. Indexes start at 0.
The last index is always len (list) - 1. Using list[len (list)] causes an IndexError.
append and insert make the list longer and del makes it shorter, so later items move to new indexes.
Build a list as the program runs: start with [], then append each new item.
print (nums) shows the brackets and commas. To show items neatly, print them one at a time in a loop.
Code (starting with nums = [40, 25, 33])
Result
nums[0]
40, the first item
nums[len (nums) - 1]
33, the last item
len (nums)
3, the number of items
nums[1] = 27
[40, 27, 33]: change an item
nums.append (18)
[40, 27, 33, 18]: add to the end
nums.insert (1, 50)
[40, 50, 27, 33, 18]: put 50 just before the item at index 1
del nums[0]
[50, 27, 33, 18]: remove the item at index 0
nums = []
an empty list (or nums = list ())
Worked exampleTrace this code and give the final list.
["Dee", "Ava", "Ben", "Cal"]insert at 0 puts Dee first
["Dee", "Ava", "Cal"]index 2 is now Ben
["Dee", "Eli", "Cal"]index 1 (Ava) replaced
["Dee", "Eli", "Cal"]
Exam tipWhen a random or calculated index picks an item, the biggest index must be len (list) - 1. Examiners saw off-by-one upper bounds that crashed programs.
Array
A sequence of items of the same (homogeneous) data type. Python uses a list.
Index
An item’s position in a list or string, starting from 0.
IndexError
The runtime error when an index is outside the list.
Edexcel 1CP2 · 6.3.1
Records and two-dimensional lists
A record is a sequence of items, usually of mixed data types. Each item is a field. In Python a record is also a list.
One record: boat = ["T02", "Canoe", 3, 42.5]. boat[1] is the field "Canoe".
A two-dimensional list is a list of lists. A table of records is a list of records: boats = [[…], […], […]].
boats[1] is a whole record. boats[1][3] is one field: the price of record 1.
Every record in a table has the same number of fields, in the same order. The PLS doesn’t use ragged lists, where rows have different lengths.
len (boats) is the number of records. len (boats[0]) is the number of fields in a record.
Add a record with boats.append (["T04", "Pedalo", 4, 30.0]). Remove one with del boats[2].
Keeping related data in one table is better than separate (parallel) lists that share an index. Parallel lists are easy to get out of step.
First index: which record (row). Second index: which field
Worked exampleUsing the table in the diagram, give the value of (a) boats[2][0] (b) boats[0][2] + boats[2][2] (c) len (boats), and write a line that changes the canoe’s price to 45.0.
(a) record 2, field 0: "T03"the third record’s code
(b) 2 + 6 = 8seats in the kayak and the raft
(c) 3three records
boats[1][3] = 45.0the canoe is record 1; price is field 3
(a) "T03" (b) 8 (c) 3; boats[1][3] = 45.0
Exam tipTwo-dimensional indexing goes row then field. Examiners see many mix-ups: write a comment such as # [code, boat, seats, price] above the table so you know each field’s index.
Record
A sequence of items, usually of mixed data types. Python uses a list.
Field
One item in a record, e.g. the price.
Two-dimensional list
A list of lists. Two indexes are needed to reach one item: table[row][field].
Edexcel 1CP2 · 6.2.2, 6.3.1
Nested loops over a two-dimensional list
To visit every item of a two-dimensional list, put one loop inside another. The outer loop goes through the records and the inner loop through the fields of each record.
for record in table: then for item in record: visits every item, row by row.
With indexes: for row in range (len (table)): then for col in range (len (table[row])):, using table[row][col].
The inner loop runs completely for each pass of the outer loop. 4 records × 3 fields = 12 passes of the inner body.
Reset a per-row total inside the outer loop, before the inner loop. Keep a grand total outside both loops.
When you only need one field from each record, you don’t need an inner loop: for record in table: then use record[2].
Worked examplesales holds the tickets sold each day (Monday to Wednesday) by three ticket booths. Write code that shows each booth’s total and the grand total.
Outer loop over booths; set boothTotal = 0 at the start of eacheach booth’s total starts from 0
Inner loop adds each day’s number to boothTotalvisits every field of the record
After the inner loop: print, and add to grandTotalone line per booth
sales = [[12, 15, 9],
[7, 11, 14],
[20, 18, 16]]
grandTotal = 0
for booth in range (len (sales)):
boothTotal = 0
for day in range (len (sales[booth])):
boothTotal = boothTotal + sales[booth][day]
print ("Booth", booth + 1, "sold", boothTotal)
grandTotal = grandTotal + boothTotal
print ("All booths:", grandTotal)
Exam tipCheck which loop each line belongs to. A total reset in the wrong place, or a print indented one level too far, gives wrong output that is easy to miss.
Edexcel 1CP2 · 6.2.2, 1.2.6
Writing a linear search
A linear search checks each item in turn until it finds the target or reaches the end. In Python, write it as a while loop with a Boolean flag, so it can stop as soon as the item is found.
Three things end the search: the item is found, the end of the list is reached, or (in a sorted list) the search has passed where the item would be.
Put all the stopping tests in the while condition. The loop then has one exit, which is easier to follow and debug than break.
A for loop over the whole list always checks every item, even after a match. That is less efficient and loses design marks in long questions.
In a list sorted into ascending order, once the current item is greater than the target, the target can’t be further on, so stop.
After the loop, use the flag to decide what to output.
The loop has one exit: the condition at the top
Worked exampleA coach company keeps the booked seat numbers for a trip in bookedSeats, sorted into ascending order. Write a search that says whether a seat number is booked, stopping early once it has passed where the seat would be.
Flags found and passed start False; index starts at 0set up before the loop
while ((not found) and (not passed) and (index < len (bookedSeats))):all three ways to stop are in one condition
Equal: found. Bigger than the target: passed. Otherwise move ononly one of the three happens each pass
bookedSeats = [4, 9, 15, 16, 23, 31]
found = False
passed = False
index = 0
seat = int (input ("Seat number: "))
while ((not found) and (not passed) and (index < len (bookedSeats))):
if (bookedSeats[index] == seat):
found = True
elif (bookedSeats[index] > seat):
passed = True
else:
index = index + 1
if (found):
print ("Seat", seat, "is booked")
else:
print ("Seat", seat, "is free")
Exam tipIn the final long question, examiners give design marks for stopping the search as soon as a match is found. A for loop that carries on to the end, or a break, works but isn’t the best design.
Linear search
Checking each item in turn, from the start, until the target is found or there are no items left.
Single exit
A loop or subprogram that can only finish in one place, e.g. when its while condition is False.
Edexcel 1CP2 · 6.2.2, 1.2.6
Common patterns: totals, counts, largest and merging
Start ‘largest’ at the first item (or at a value lower than any possible item). Starting at 0 fails if every item is negative.
To remember which record was largest, also store its name (or index) when you update the largest value.
Check that a count isn’t 0 before dividing by it, or you get a ZeroDivisionError.
Merging two sorted lists (the merge step of merge sort): while both lists have items left, compare the front items and append the smaller, moving that list’s index on. Then copy whatever is left in either list.
Pattern
Before the loop
Inside the loop
Total
total = 0
total = total + item
Count matching items
count = 0
if (item > 50): count = count + 1
Largest
biggest = items[0]
if (item > biggest): biggest = item
Mean
total and count
after the loop: mean = total / count (only if count > 0)
Pearson expects you to be able to code this merge with while loops
Worked exampleWrite code to merge two sorted lists into one sorted list, using while loops.
indexA and indexB start at 0; merged = []one index for each list
while ((indexA < len (listA)) and (indexB < len (listB))):both lists still have items
Append the smaller front item; add 1 to that list’s indexthe result stays in order
Two more while loops copy what’s leftonly one of them will have items
listA = [3, 8, 12]
listB = [5, 6, 14, 20]
merged = []
indexA = 0
indexB = 0
while ((indexA < len (listA)) and (indexB < len (listB))):
if (listA[indexA] <= listB[indexB]):
merged.append (listA[indexA])
indexA = indexA + 1
else:
merged.append (listB[indexB])
indexB = indexB + 1
while (indexA < len (listA)):
merged.append (listA[indexA])
indexA = indexA + 1
while (indexB < len (listB)):
merged.append (listB[indexB])
indexB = indexB + 1
print (merged)
Exam tipGo through the data once. A design that loops through a table three times (once for the total, once for the largest, once to print) loses design marks. One loop can do all three jobs.
Merge
Combining two sorted lists into one sorted list by repeatedly taking the smaller front item.