In a predict and run task you do not write code from scratch. You start from a small piece of working code, work out what you think it will do before you run it, and then run it to check whether you were right.
Three students take a spelling test every week, and a program stores their
results in a 2D array called scores. Each row is one student: their name
first, then their marks in four tests.
scores = [
["Bob", 5, 9, 10, 7],
["Mary", 4, 10, 3, 6],
["James", 7, 6, 4, 8]
]
Every example below starts from this array.
For every example, study the code carefully and write down a prediction before
you touch the Run button. Your prediction should use the key terms 2D
array, row, column and index. It helps to draw the array as a
table first and number its rows and columns, starting from 0. You can type your
prediction straight into the code as a comment, on a line starting with #.
Only once you have written your prediction should you run the code and compare the result with what you expected.
scores = [
["Bob", 5, 9, 10, 7],
["Mary", 4, 10, 3, 6],
["James", 7, 6, 4, 8]
]
print(scores[0][0])
Predict the one line this prints. Which row and which column does [0][0]
point at?
scores = [
["Bob", 5, 9, 10, 7],
["Mary", 4, 10, 3, 6],
["James", 7, 6, 4, 8]
]
print(scores[1][3])
Predict the number this prints. Count carefully: the name takes up column 0, so which test’s mark is in column 3, and whose?
scores = [
["Bob", 5, 9, 10, 7],
["Mary", 4, 10, 3, 6],
["James", 7, 6, 4, 8]
]
print(scores[1][0] + " " + str(scores[1][4]))
This one joins two items and a space with +. One of the items is a number,
so it is wrapped in str() first. Predict the output.
Mary 6
scores[1][0] is the text "Mary" and scores[1][4] is the whole number
6. A 2D array can hold text and numbers side by side, and each item keeps
its own data type, so the number is wrapped in str() before it is joined
onto text with +.
scores = [
["Bob", 5, 9, 10, 7],
["Mary", 4, 10, 3, 6],
["James", 7, 6, 4, 8]
]
scores[2][3] = 9
scores[0][3] = 6
scores[1][0] = "Alice"
print(scores)
Before you run it, write out the whole array as it will look after lines 7 to 9
have run, one row per line, the same way it is written at the top. Then run it
to check: print(scores) prints the whole array on one line.
scores = [
["Bob", 5, 9, 6, 7],
["Alice", 4, 10, 3, 6],
["James", 7, 6, 9, 8]
]
James’s third test changes from 4 to 9, Bob’s from 10 to 6, and Mary’s name is
replaced by Alice. Each assignment overwrites exactly one item, and the array
keeps its three rows of five.
Printed, the whole array comes out on one line:
[['Bob', 5, 9, 6, 7], ['Alice', 4, 10, 3, 6], ['James', 7, 6, 9, 8]]
Make sure that you check for the following things:
str() before they are joined onto text with a +.