KS4J277 2.2.2 20 min read 10 question quiz 17 exam marks

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 typeHoldsExamples
IntegerA whole number, positive or negative42, -7, 0
Real or floatA number with a decimal part3.14, -0.5, 2.0
BooleanOne of two values onlyTrue, False
CharacterA single character"A", "7", "?"
StringA 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
Phone numbers are strings

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

  1. Memory. An integer uses less memory than a real. Across a database of millions of records the difference is substantial.
  2. Correct operations. You cannot multiply strings, and you cannot concatenate integers. Using the wrong type causes errors.
  3. Validation. Declaring a value as an integer means non numeric input is rejected automatically in many languages.
  4. Accuracy. Reals are stored as approximations, so money is sometimes stored as an integer number of pence to avoid rounding errors.
The data types, and changing one into anotherThe five basic data types, one card each. An integer is a whole number such as 42, written int in Python. A real number has a decimal point such as 3.14, written float. A Boolean has only two values, True and False, shown as a switch that is on and a switch that is off. A character is a single symbol such as the letter A, and a string is text inside quote marks. A phone number is stored as a string, because you never do arithmetic on it and because storing it as a number would drop the leading zero, turning 07700 into 7700. Casting changes a value from one type to another: int of the text 42 gives the number 42, str of the number 42 gives the text 42, and int of 3.9 gives 3 because the decimal part is cut off rather than rounded.Integer42-7 0 2025whole numbersintReal3.140.5 -2.75with a decimal pointfloatBooleanTrue Falseonly two valuesboolCharacterAz 7 ?one single symbolstrString"Hi""07700 900123"text in quotesstr1A phone number is a string07700900123you never add phone numbersa number would lose the 007700 as a number = 7700so it is stored as text2Casting: changing type"42"int()42to a whole number42str()"42"to text3.9int()3cuts off the .93
  1. Five data types: integer, real, Boolean, character and string.
  2. A phone number is a string: you never add them, and a number would lose the leading 0.
  3. Casting changes a value from one type to another: int(), str(), float().
Choose the type from what you will do with the value, not from how it looks.

Casting

Casting is converting a value from one data type to another.

Python
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 True

Why casting is needed

input() always returns a string, even when the user types a number. Without casting:

Python
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:

Python
a = input("First number: ")   # user types 5
b = input("Second number: ")  # user types 3
print(a + b)                  # prints 53, not 8

The + operator joins strings together. Both values must be cast to integers first.

Python
a = int(input("First number: "))
b = int(input("Second number: "))
print(a + b)                  # prints 8

Casting the other way

When printing a number joined to text in Python you must cast to string:

Python
score = 42
print("Your score is " + str(score))   # correct
The rule to remember

input() gives a string. Cast to int() or float() before doing arithmetic or numeric comparison. Cast to str() before joining a number to text with +.

Casting between types: int, float and str, and when it failsCasting converts a value from one data type to another. int of the text 42 gives the whole number 42. int of 3.7 gives 3, because it cuts off the decimal part and does not round. str of the number 5 gives the text 5, so it can be joined to words. float of the text 3.14 gives the decimal number 3.14. The input function always gives back text, so a number typed by a user must be converted, as in age equals int of input. Some conversions fail: int of the text hello raises a ValueError, so input should be checked before it is converted.int("42")42stringint()42integertext to a whole numberint(3.7)3.7floatint()3integercuts off the decimal part: it does not roundstr(5)5integerstr()"5"stringa number to text, so it can be joined to wordsfloat("3.14")"3.14"stringfloat()3.14floattext to a decimal number1234input() always gives text5age = int(input("Age? "))print(age + 1)convert it before doing sums with itSome conversions fail6Output>>> int("hello")ValueError: invalid literalso check the input before converting it
  1. int() turns text into a whole number.
  2. int() on a float cuts off the decimals. It does not round.
  3. str() turns a number into text.
  4. float() turns text into a decimal number.
  5. input() always returns text, so convert it before doing sums.
  6. A conversion that does not make sense raises an error, so validate first.
Casting does not change the original. It makes a new value of the type you asked for.

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.

DefineInteger
AnswerA whole number data type, with no fractional part.
DefineReal
AnswerA data type for numbers with a decimal part. Also called float.
DefineBoolean
AnswerA data type with only two possible values, true and false.
DefineCharacter
AnswerA data type holding a single character.
DefineString
AnswerA data type holding a sequence of characters.
DefineCasting
AnswerConverting a value from one data type into another.
DefineConcatenation
AnswerJoining two strings together to form one longer string.

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

Avoid these
  • 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.
Fun fact

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

0 of 10 answered
1Which data type should be used to store whether a light is switched on?
2Why should a phone number be stored as a string rather than an integer?
3What does int("57") produce?
4A program uses a = input() and b = input(), then print(a + b). The user types 4 and 6. What is printed?
5Which data type is most suitable for a product price of 9.99?
6What is casting?
7Which is a valid reason for choosing the correct data type?
8How many possible values can a Boolean hold?
9In Python, what is needed to print "Score: " + score where score is an integer?
10A student's exam mark out of 100 with no decimals should be stored as:
Score 0 / 10

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.

17 marks
1State the most appropriate data type for each of the following and justify one of your choices: a customer's surname, whether an order has been dispatched, the total price of an order.4 marks
State

Mark scheme0 / 4
  • LSurname is a string
  • LDispatched is a Boolean
  • LTotal price is a real
  • LGives a valid justification for one choice
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2A program asks the user for two numbers and adds them together, but when the user enters 12 and 5 the program outputs 125. Explain why this happens and how the programmer could correct it.3 marks
Explain

Mark scheme0 / 3
  • LThe input function returns a string
  • LThe plus operator concatenates strings rather than adding numbers
  • LCast the inputs to integers using int() before adding
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain two reasons why choosing an appropriate data type is important when writing a program.4 marks
Explain

Mark scheme0 / 4
  • 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
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4Define the term casting and give an example of when it would be needed.3 marks
Define

Mark scheme0 / 3
  • 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
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5A programmer stores a student's ID number, which always begins with a zero, as an integer. Explain the problem this causes and state what should be used instead.3 marks
Explain

Mark scheme0 / 3
  • LAn integer does not preserve leading zeros
  • LThe ID would be stored or displayed incorrectly
  • LA string should be used instead
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 17