Data Types and Casting
The five data types you must know, why choosing the right one saves memory, and why casting is the fix for the most common bug in beginner programs.
The five data types
| Data type | Holds | Examples |
|---|---|---|
| Integer | A whole number, positive or negative | 42, -7, 0 |
| Real or float | A number with a decimal part | 3.14, -0.5, 2.0 |
| Boolean | One of two values only | True, False |
| Character | A single character | "A", "7", "?" |
| String | A sequence of characters | "Hello", "CS123", "" |
Choosing correctly
Ask what the data actually is and what you will do with it.
- A person's age: integer, since ages are whole numbers
- A price: real, since it needs pence
- Whether a user is logged in: Boolean, only two states
- A phone number: string, not integer, because it may start with 0 and you never do arithmetic on it
- A postcode: string, because it contains letters
Store 07700 900123 as an integer and the leading zero disappears. Any number you never perform arithmetic on should be a string.
Why the right type matters
- Memory. An integer uses less memory than a real. Across a database of millions of records the difference is substantial.
- Correct operations. You cannot multiply strings, and you cannot concatenate integers. Using the wrong type causes errors.
- Validation. Declaring a value as an integer means non numeric input is rejected automatically in many languages.
- Accuracy. Reals are stored as approximations, so money is sometimes stored as an integer number of pence to avoid rounding errors.
- Five data types: integer, real, Boolean, character and string.
- A phone number is a string: you never add them, and a number would lose the leading 0.
- Casting changes a value from one type to another: int(), str(), float().
Casting
Casting is converting a value from one data type to another.
age_text = input("How old are you? ") # this is a STRING, always
age = int(age_text) # now it is an integer
price = float("19.99") # string to real
label = str(42) # integer to string
flag = bool(1) # 1 becomes TrueWhy casting is needed
input() always returns a string, even when the user types a number. Without casting:
age = input("Age: ") # user types 20, age is the string "20"
if age > 18: # ERROR: cannot compare a string with a number
print("Adult")And this:
a = input("First number: ") # user types 5
b = input("Second number: ") # user types 3
print(a + b) # prints 53, not 8The + operator joins strings together. Both values must be cast to integers first.
a = int(input("First number: "))
b = int(input("Second number: "))
print(a + b) # prints 8Casting the other way
When printing a number joined to text in Python you must cast to string:
score = 42
print("Your score is " + str(score)) # correctinput() gives a string. Cast to int() or float() before doing arithmetic or numeric comparison. Cast to str() before joining a number to text with +.
- int() turns text into a whole number.
- int() on a float cuts off the decimals. It does not round.
- str() turns a number into text.
- float() turns text into a decimal number.
- input() always returns text, so convert it before doing sums.
- A conversion that does not make sense raises an error, so validate first.
Key terms you must be able to define
- Integer
- A whole number data type, with no fractional part.
- Real
- A data type for numbers with a decimal part. Also called float.
- Boolean
- A data type with only two possible values, true and false.
- Character
- A data type holding a single character.
- String
- A data type holding a sequence of characters.
- Casting
- Converting a value from one data type into another.
- Concatenation
- Joining two strings together to form one longer string.
Flashcards
Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.
Reach the top grade on this topic
The knowledge here is short, so precision earns the marks.
Justify a data type by what you will do with the value. Not "a phone number is a string because it has numbers in it", but "a phone number is stored as a string because it may begin with a zero, which an integer would discard, and because no arithmetic is ever performed on it".
Be exact about why casting is needed. The reason is that input() always returns a string, and the + operator concatenates strings rather than adding them, so the program produces "53" instead of 8.
Know the memory argument. Choosing the smallest suitable type reduces memory use, which is significant across large datasets and important on constrained devices.
- Choose and justify a data type for any given piece of data
- Explain exactly what goes wrong when input is not cast, with the actual output
- Give three reasons why choosing the right data type matters
Mistakes that cost marks here
- Storing a phone number or a postcode as an integer.
- Saying casting 'changes the variable name'. It converts the value's type.
- Forgetting that input() returns a string even when the user types digits.
- Using a real for a value that is always whole, wasting memory.
- Saying a Boolean can hold yes, no or maybe. It has exactly two values.
Storing a whole number as a real wastes memory and can also lose accuracy. Some decimal fractions cannot be represented exactly in binary, which is why 0.1 plus 0.2 does not quite equal 0.3 in most programming languages.
Knowledge check
int("57") produce?a = input() and b = input(), then print(a + b). The user types 4 and 6. What is printed?"Score: " + score where score is an integer?Exam-style questions
Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.
- LSurname is a string
- LDispatched is a Boolean
- LTotal price is a real
- LGives a valid justification for one choice
A customer's surname should be stored as a string, because it is a sequence of characters and no arithmetic is ever performed on it. Whether an order has been dispatched should be stored as a Boolean, because there are only two possible states, dispatched or not dispatched, and a Boolean uses the least memory of any type while making the meaning of the value completely clear. The total price of an order should be stored as a real, because prices include pence and therefore require a fractional part that an integer could not represent.
- LThe input function returns a string
- LThe plus operator concatenates strings rather than adding numbers
- LCast the inputs to integers using int() before adding
The problem is that the input function always returns a string, even when the user types digits, so the variables hold the strings "12" and "5" rather than the numbers 12 and 5. When the plus operator is applied to two strings it concatenates them, joining them end to end, which produces "125" rather than performing addition. The programmer should cast each input to an integer as it is read, for example using number1 = int(input(...)), so that the values are stored as integers and the plus operator then performs numerical addition, producing 17.
- LDifferent types use different amounts of memory
- LChoosing the smallest suitable type saves memory, which matters across large amounts of data
- LThe data type determines which operations are valid
- LUsing the wrong type causes errors or incorrect results
The first reason is memory efficiency. Different data types require different amounts of storage, with a Boolean needing very little and a real needing considerably more than an integer, so choosing the smallest type that can hold the data reduces the memory the program uses. Across a database holding millions of records, or on an embedded device with very limited memory, that difference is significant. The second reason is that the data type determines which operations can validly be carried out on a value. Arithmetic can be performed on integers and reals but not on strings, and concatenation applies to strings but not to numbers, so storing a value with the wrong type either causes the program to raise an error or, worse, produces a plausible but incorrect result, such as two numbers being joined together instead of added.
- LCasting is converting a value from one data type to another
- LGives a valid example such as converting user input to an integer
- LExplains why it is needed in that example
Casting is the process of converting a value from one data type into another, for example turning the string "25" into the integer 25. It is needed whenever a value is held as one type but must be used as another. A common example is reading a number from the user: the input function returns a string, so before the program can perform any arithmetic or numerical comparison on that value it must be cast using int() or float(), otherwise the program will either produce an error or treat the value as text and concatenate it rather than adding it.
- LAn integer does not preserve leading zeros
- LThe ID would be stored or displayed incorrectly
- LA string should be used instead
Storing the ID as an integer causes the leading zero to be lost, because numerically 0451 and 451 are the same value and an integer stores only the numeric value with no record of how it was written. This means the ID would be displayed and stored as 451, which does not match the student's actual ID and would cause lookups against records held elsewhere to fail. The ID should be stored as a string instead, which preserves every character exactly as entered, and this is appropriate because no arithmetic is ever performed on an ID number.