GCSE Revision

Data types and casting

Choosing a data type

A data type tells you what kind of value a variable stores. Choose one that suits the value:

TypeUse it forERLPython
IntegerWhole numbers, such as a score or countINTEGERint
RealMeasurements or other numbers with a fractional partREALfloat
BooleanA yes/no state or a conditionBOOLEANbool
CharacterOne letter, digit or symbolCHARACTERA one-character str
StringText with zero or more charactersSTRINGstr

Python infers types from assigned values. Both characters and strings use str in Python; use a character when exactly one symbol is intended. For example, count = 12 is an integer and height = 1.65 is a real/float.

count = 12
height = 1.65
ready = count > 0
initial = "A"
name = "Ada"

Key terms

Casting input to a number

When a program reads a number from the keyboard, convert the input text before doing arithmetic. Use int() when the answer must be a whole number and float() when it may contain a decimal point:

INPUT age
INPUT height
OUTPUT age + 1
OUTPUT height

With inputs 15 and 1.6, the program outputs 16 and 1.6. In Python, int("15") works, but int("1.6") raises ValueError; use float("1.6") for a decimal. If unconverted input is added to a number, Python reports a type error.

Key terms

Casting between types

Casting changes a value from one data type to another:

CastExampleResult
To a stringstr(42)"42"
To an integerint("15")15
To a realfloat("2.5"), or real("2.5") in ERL2.5
To a Booleanbool("True") in ERLtrue

Cast to a string to join a number onto text, as in "Score: " + str(score). Cast to a number before doing arithmetic or comparing values as numbers.

In Python, bool() of any non-empty string is True, even bool("False"), so compare the text instead: answer == "True".

Why the type matters

Strings are compared character by character, not as numbers. So "10" < "9" is true: the first characters are compared, and "1" comes before "9". As numbers, 10 < 9 is false.

This matters whenever a program sorts or compares values typed in by a user. Cast the inputs to numbers first, and the comparison works as expected.

Common mistake

A phone number is stored as a string, not an integer: it's never used in arithmetic, and an integer would lose its leading 0.

Take the quiz