Records
A record is one item's worth of related data split into fields. In Python you can hold a single record in a one-dimensional array, which is just a list with one field per element. The record below describes one bike hired from a cycle shop: its bike ID, the customer's surname, the number of hours hired and whether the bike came back damaged.
bike = ["BK-2290", "Ahmed", "3", "False"]
# field order: bike ID, customer surname, hours hired, damaged
print(bike[1])
print(bike[2] + " hours hired")Output:
Ahmed
3 hours hiredThe order of the fields is fixed, and it is the program that has to remember it. For this record, element 0 is the bike ID, element 1 the customer's surname, element 2 the hours hired and element 3 the damaged flag. Nothing in the list labels those positions, so swapping two fields would silently break every line of code that uses the record.
A real record can mix data types: text, whole numbers, real numbers and Boolean values. An array can hold only one data type, so a record held in a one-dimensional array stores every field as a string. The bike record holds "3" as text, not as a number, and the damaged flag is held as the text "False", not as a Boolean.
That has three consequences you must handle:
int() or float() before you add them, compare them with a number or use them in any calculation."True" or "False", so you compare it as text, for example bike[3] == "True", rather than treating it as a real Boolean value.+ for output, with no casting needed.Comparing bike[2] == 3 is always false: the string "3" and the number 3 are different things, even though they look alike. Cast first, then compare.
Once the fields are cast, the record behaves like any other data. Here the hours hired are turned into a number, compared with a limit, and the surname is used in messages without any casting at all.
bike = ["BK-2290", "Ahmed", "3", "False"]
hours = int(bike[2])
if hours >= 3:
print(bike[1] + " has reached the time limit")
if bike[3] == "True":
print(bike[1] + " must pay for damage")Output:
Ahmed has reached the time limit OCR GCSE Computer Science · Records