Menu

Data Types

Choosing Data Types

Choosing a data type means picking the type that fits both the value you need to store and the way your program will use it. A variable holding the number of lengths swum in a pool needs a numeric type; a variable holding a swimmer's name needs a text type.

Matching the type to the job

Integer and real values are used for arithmetic, such as adding or dividing. Boolean values are used in conditions, where only true or false makes sense. Character and string values are used for text. Get the match right and the operations you use on the variable make sense.

Value to storeSensible type
Number of swimmers in a laneinteger
Length of a race, 50.5 metresreal
Whether a swimmer has finishedBoolean
Lane letter C (one character)character, held in Python as the string "C"
Swimmer's full namestring
# a swimming race program stores one value of each type it needs
lane_letter = "C"      # character: one character, held as a string
race_length = 50.5     # real: can have a fractional part
swimmers = 6           # integer: counted and added to
finished = False       # Boolean: only True or False

Why the wrong type causes trouble

If the type does not suit the data, the program can produce incorrect results or fail with an error. Joining two strings that look like numbers glues the text together instead of adding it, so "8" + "5" gives "85" rather than 13. Adding a number to a string stops the program with an error.

swimmers = "6"
total = swimmers + 1   # text cannot be added to an integer
print(total)

Output:

TypeError: can only concatenate str (not "int") to str (line 2)

Memory and starting values

The data type also affects how much memory is allocated to the variable: a real number generally needs more space than an integer, and a string needs room for each character it holds. Choosing the most suitable type keeps memory use down.

When you initialise a variable, the starting value should be of the intended type. A score that will be added to should start as 0 rather than "", and a finished flag should start as False. Starting a numeric total as "" makes the first addition fail.

Practise this