Menu

Records

Totalling and updating numeric fields

In Python, a table of records is held as a list of lists, and every field is stored as a string, so a numeric field like a score or a price is really text that looks like a number. To total that field, you build a running total in a number variable, then cast the answer back to text for output.

Totalling a field

Three steps, in this order:

  1. Set the total to 0 before the loop, so the first record is added to nothing.
  2. Inside the loop, add int() of the field for each record.
  3. After the loop, wrap the finished total in str() so it can be joined to text in print().

Step 2 matters because "7" + "3" gives "73", not 10, and 0 + "7" stops the program with a TypeError: Python will not add a string to a number. The cast tells Python to read the field as a whole number. Step 3 matters for the same reason in reverse: print("Total: " + 24) fails, because you cannot join text to an integer.

Here each player's score is stored at column 2, so the loop below casts every score as it adds it.

scores = [["Ade", "Red", "18"], ["Mira", "Blue", "25"], ["Tom", "Red", "9"]]
total = 0
for record in scores:
    total = total + int(record[2])
print("Total points: " + str(total))

Output:

Total points: 52

Updating a field

To update a field, find the record you want, then assign a new value to that one element using [record][field]. You overwrite what was there, so the rest of the record is untouched.

A numeric update is cast both ways: int() to take the old value out and calculate with it, then str() to put the new value back, because the element must stay a string like every other field in the table. A plain number stored there would crash the next program that joined that field to text.

Here the club at index 1, column 2 gains 4 members.

clubs = [["Drama", "Hall", "24"], ["Chess", "Lab 2", "12"], ["Robotics", "Workshop", "18"]]
chosen = 1
joined = 4
count = int(clubs[chosen][2])
count = count + joined
clubs[chosen][2] = str(count)
print(clubs[chosen][0] + " members: " + clubs[chosen][2])

Output:

Chess members: 16

Notice that count is a number while you work with it, and only becomes text again when it is stored back into the table.

Practise this