Beginner

Data Types and Casting

AicademyAicademy
·OCR GCSE Computer Science·OCR J277·7 min
2.2.2 Data types

Why Data Types Matter

Every value stored in a program has a data type that determines what kind of data it is, how much memory it uses, and what operations are valid on it. OCR J277 requires knowledge of five data types.

Data typeWhat it storesExample values
IntegerWhole numbers, positive or negative0, 42, -7, 1000
RealNumbers with a decimal (fractional) part3.14, -0.5, 99.99
BooleanA true or false valueTrue, False
CharacterA single character'A', '7', '!'
StringA sequence of zero or more characters"hello", "Y10", ""

Choosing the wrong data type causes errors. Storing a price as an integer (e.g. price = 2) loses the decimal part. Storing a name as an integer is impossible.

The data type must match the nature of the data, not just the current value. An exam score of 85 is an integer; a measurement of 1.85 m is a real.

Integer and Real

Integer — stores whole numbers with no decimal point. Use integers for things that are counted or indexed.

age = 17
num_students = 30
high_score = 9999

Real (also called float in Python) — stores numbers with a decimal part. Use reals for things that are measured or calculated with division.

temperature = 36.6
average = 78.5
pi = 3.14159

Worked example — choosing between integer and real:

ScenarioData typeReason
Number of lives remaining in a gameIntegerLives are counted whole — you can't have 2.5 lives
Price of an item (£3.99)RealPrices have pence — a decimal is needed
Student's test score out of 100IntegerScores are whole marks
Distance run in kilometres (5.4 km)RealDistances are measured, not counted
Number of items in a shopping basketIntegerItems are counted whole

If a value could ever be non-whole — a measurement, a price, a ratio — use real. If it will always be a whole count, use integer.

Boolean and Character

Boolean stores exactly one of two values: True or False. Booleans are the result of comparison expressions and control selection/iteration.

logged_in = False
game_over = False
is_valid = age >= 18      # True if age is at least 18, False otherwise

Booleans are used directly in conditions:

if logged_in:
    print("Welcome back")

Character stores a single symbol — a letter, digit, punctuation mark, or space. In most languages a character is written in single quotes.

grade = 'A'
initial = 'J'
separator = ','

A character is not the same as a single-character string. 'A' (character) and "A" (string of length 1) behave identically in Python, but the distinction matters when the spec or an exam question uses the term explicitly.

TypeValue exampleValid operations
BooleanTrueAND, OR, NOT; used in IF conditions
Character'B'Comparison ('A' < 'B'), concatenation into strings

Strings — Sequences of Characters

A string is an ordered sequence of zero or more characters. Strings store text: names, messages, codes.

name = "Alice"
empty = ""            # zero characters — still a valid string
postcode = "SW1A 1AA"

String-specific operations (covered in full in the string manipulation lesson):

  • Length: len("hello") returns 5
  • Indexing: "hello"[0] returns 'h' (zero-indexed)
  • Concatenation: "hello" + " " + "world" returns "hello world"

Type gotcha — numbers stored as strings:

a = "5"
b = "3"
print(a + b)     # prints "53" — string concatenation, NOT addition

Storing a number as a string prevents arithmetic. The + operator on strings concatenates rather than adds.

When reading input from a user with input(), the result is always a string. Convert it with int() or float() before doing arithmetic.

Worth saving these ideas?

Turn what you've read into instant revision cards. Free to get started.

Make flashcards

Casting — Temporarily Changing Data Types

Casting converts a value from one data type to another. The conversion is temporary — it produces a new value of the target type without changing the original variable's type.

Common casting operations:

FunctionConverts toExampleResult
int(x)Integerint("42")42
int(x)Integerint(3.9)3 (truncates, does not round)
float(x)Realfloat("3.14")3.14
str(x)Stringstr(100)"100"
bool(x)Booleanbool(0)False

Worked example — casting to perform arithmetic on user input:

age_str = input("Enter your age: ")   # returns "17" as a string
age = int(age_str)                    # cast to integer
birth_year = 2026 - age              # arithmetic now works
print("Born in", str(birth_year))    # cast back to string for output message

Without int(), 2026 - age_str would cause a TypeError because you cannot subtract a string from an integer.

int(3.9) gives 3, not 4. Casting truncates toward zero — it does not round. Use round() if rounding is needed.

Choosing the Right Data Type

Exam questions frequently present a scenario and ask you to identify the most appropriate data type for each piece of data.

Worked example — a school database stores student records with these fields:

FieldValue exampleBest data typeReason
Student ID10245IntegerWhole number, used for identification
Full name"Ahmed Khan"StringText — sequence of characters
Year group11IntegerCounted whole number
Average grade (%)72.5RealMay have a decimal
Has parental consentTrueBooleanOnly two possible values: yes/no
Form tutor initial'S'CharacterSingle letter
Date of birth"2009-04-15"StringText representation of a date

Date of birth is stored as a string in simple programs because date arithmetic is complex. A more advanced system would use a dedicated date type, but this is beyond OCR J277 scope.

Common Exam Mistakes

1. Choosing integer for prices or measurements

£3.99 cannot be stored as an integer without losing the pence. Whenever a value has a decimal, choose real.

2. Confusing character and string

A character is exactly one symbol. A string can be any length, including zero. If a field holds a name, it is a string. If it holds a single initial, it may be a character.

3. Forgetting that input() always returns a string

User input is always a string in Python. If you need to compare it to a number or use it in arithmetic, cast it first: int(input(...)).

4. Thinking int() rounds to the nearest whole number

int(3.9) returns 3, not 4. Casting to integer truncates (drops the decimal). To round, use round(3.9) which returns 4.

MistakeCorrection
Storing price £4.99 as integerUse real — it has a decimal part
age = input(...) then 2026 - ageCast first: age = int(input(...))
int(7.8) == 8int(7.8) == 7 — casting truncates, it does not round

Generate revision on any topic you study

Type any topic you're studying and Aicademy generates a complete lesson, quiz, and flashcard set — personalised to your level.

Lessons on anything

Structured, level-matched lessons on any topic you study

Practice quizzes

Find out what you actually know before the exam does

Flashcard sets

Lock in key concepts with instant revision cards

Ask Aica

Stuck on something? Get a clear explanation, any time

Prev

Programming Fundamentals

Next

String Manipulation and File Handling

Related lessons

7 Slides

Lesson

Programming Fundamentals

OCR GCSE Computer Science · OCR J277

4 days ago

7 Slides

Lesson

String Manipulation and File Handling

OCR GCSE Computer Science · OCR J277

4 days ago

7 Slides

Lesson

Arrays and Records

OCR GCSE Computer Science · OCR J277

4 days ago

7 Slides

Lesson

Number Systems and Data Units

OCR GCSE Computer Science · OCR J277

3 days ago