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:
| Type | Use it for | ERL | Python |
|---|---|---|---|
| Integer | Whole numbers, such as a score or count | INTEGER | int |
| Real | Measurements or other numbers with a fractional part | REAL | float |
| Boolean | A yes/no state or a condition | BOOLEAN | bool |
| Character | One letter, digit or symbol | CHARACTER | A one-character str |
| String | Text with zero or more characters | STRING | str |
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:
| Cast | Example | Result |
|---|---|---|
| To a string | str(42) | "42" |
| To an integer | int("15") | 15 |
| To a real | float("2.5"), or real("2.5") in ERL | 2.5 |
| To a Boolean | bool("True") in ERL | true |
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.