23 exam-style questions plus unlimited generated ones on this topic, at up to four difficulty levels, with full mark schemes. Notes and past-paper booklets are open to everyone. Practice needs a free account.
Or take a quick quiz: 10 questions on this subtopic in GCSE Computer Science (Edexcel), marked as you tap.
How a program stores data: the data types integer, real, Boolean, character and string, variables and constants, and the data structures you use in Python (lists for one- and two-dimensional arrays, and records). You also need to manipulate strings: their length, the position of characters, substrings, and upper and lower case.
Key facts
Integer: whole number (int). Real: number with a decimal part (float)
Boolean: True or False (bool). Character: one symbol. String: text (str)
Variable: value can change. Constant: value fixed while the program runs
Casting: int(), float(), str()
List indexes start at 0; the last index is len(list) − 1
Two-dimensional list: name[row][column]
Record: related fields of different data types, e.g. ["Kai", 15, True]
Real(float): a number with a decimal part, e.g. 3.75.
Boolean(bool): only True or False.
Character: a single letter, digit or symbol, e.g. "Y". Python stores it as a string of length 1.
String(str): a sequence of characters, e.g. "CB4 1PQ". Phone numbers are strings: they can start with 0 and you never do maths with them.
Casting converts between types: int("42") gives 42, float("2.5") gives 2.5 and str(7) gives "7".
Variables and constants
A variable is a named location in memory whose value can change while the program runs.
A constant holds a value that does not change while the program runs, e.g. VAT_RATE = 0.2. Python does not stop you changing it, so constant names are written in capitals to show they should not be changed.
Constants make code easier to read and maintain: to change the value you edit one line, not every place it is used.
Arrays and records
diagram
An array holds many items under one identifier, and each item has an index starting at 0. Python uses lists: in scores = [12, 9, 15],scores[0] is 12.
Each item in a list has an index, counted from 0.
len(scores) gives the number of items; scores.append(20) adds an item to the end; scores[1] = 10 changes an item.
A two-dimensional array is a list of lists, like a table: grid[1][2] is row 1, column 2, both counted from 0.
grid = [[4, 7, 1, 9], [3, 8, 6, 2], [5, 0, 2, 7]]: the row index comes first, then the column index.
A record groups related fields that can have different data types, e.g. ["Kai", 15, True] for a name, an age and whether the person is a member. A list of records is two-dimensional: club[2][0] is the name in the third record.
Manipulating strings
diagram
Length: len("Python") is 6.
Position: characters are indexed from 0, so word[0] is the first character. word.find("t") gives the index of the first t, or −1 if there is none.
Substring: word[1:4] gives the characters at indexes 1, 2 and 3 (it stops before 4). For "Python" this is "yth".
A slice starts at the first index and stops before the second.
Case conversion: word.upper() gives "PYTHON" and word.lower() gives "python". The variable only changes if you assign the result: word = word.upper().
Ask what values the data can take: whole numbers, decimals, two options, or text.
Anything you would never calculate with, such as a phone number, is a string.
Use the names integer, real, Boolean, character and string.
Example. A gym stores data about each member. State the most suitable data type for each item. (a) The member's surname (1) (b) The monthly fee, e.g. 24.99 (1) (c) Whether the member has paid this month (1) (d) The number of visits this month (1)
Show the model answerHide the model answer
(a) String
(1)
(b) Real (float)
(1)
(c) Boolean
(1)
(d) Integer
(1)
Explain why a constant is used
2 marksGrade 5
Say what a constant is: a value that does not change while the program runs.
Give a benefit and link it to the program in the question.
Example. A game program uses the constant MAX_PLAYERS = 4 in several places. Give two reasons why a constant is used instead of typing 4 each time. (2)
Show the model answerHide the model answer
If the maximum number of players changes, the value only has to be changed in one place
(1).
The name MAX_PLAYERS makes the code easier to understand than the number 4 on its own
(1).
State the output of string operations
1 mark eachGrade 6
Write the string out and number each character from 0.
For a slice [a:b], take the characters from index a up to, but not including, index b.
Write the output exactly, with the correct upper or lower case.
Example.
city = "Cardiff"
State the output of each statement. (a) print(len(city)) (1) (b) print(city[2:5]) (1) (c) print(city.upper()) (1) (d) print(city.find("f")) (1)Show the model answerHide the model answer
(a) 7
(1)
(b) rdi
(1)
(c) CARDIFF
(1)
(d) 5: the first f is at index 5
(1)
Use a two-dimensional list
3 to 5 marksGrade 7
Remember the order: row index first, then column index, both from 0.
To visit every item, use a loop over the rows with a loop over each row's items inside it.
Make the code work for any size: loop over the list itself or use len(), not fixed numbers.
Example. Each row of this list holds the sales of one shop over three days.
sales = [[12, 8, 15], [9, 14, 11]]
(a) State the value of sales[1][0]. (1) (b) Write code that outputs the total of all the values in sales. Your code must work for any number of rows and columns. (3)Show the model answerHide the model answer
(a) 9
(1)
(b)
total = 0
for row in sales:
for value in row:
total = total + value
print(total)
Sets total to 0 before the loops (1); nested loops that visit every value in every row (1); adds each value to total and outputs it after the loops (1). For this list the output is 69.
Don’t lose marks
Storing a phone number as an integer, which loses the leading 0.
Counting indexes from 1. The first item is at index 0.
Forgetting that input() and data from a file are strings: "5" + "3" is "53", not 8.
Thinking upper() or lower() changes the variable by itself. You must assign the result.
Mixing up the row and column indexes in a two-dimensional list.
Giving 'number' or 'decimal' as a data type. Say integer or real.
More tips
Memory tricks
If you would never do maths with it (phone number, postcode, ID with leading zeros), store it as a string.
Slicing [a:b]: a is in, b is out, and the slice has b − a characters.
Row then column, like reading a table: go down to the row, then along to the column.
find() gives −1 when the character is not there, a quick way to check whether a string contains it.
Constant names in CAPITALS, so you spot them straight away.
Exam technique
When you justify a data type, link it to the data: 'real, because the price has a decimal part'.
Before working out a slice or an index, write the index of each character above the string.
Code that processes a list should work for any length: loop over the list or use len(), never a fixed number.
Keep the order of fields in a record exactly as the question gives it, e.g. name at index 0, age at index 1.
What each grade needs
What you need to be able to do, from the first marks up to the top grade.
Grade 3
Name the primitive data typesInteger, real, Boolean and character, which Python stores as int, float, bool and str.
Grade 4
Choose a suitable data type for dataE.g. real for a price, Boolean for yes or no, string for a phone number.
Grade 4
Explain the difference between variables and constantsA variable's value can change while the program runs; a constant's value cannot.
Grade 5
Convert between data types by castingUse int(), float() and str() before calculating or joining text.
Grade 5
Access and change items in a listUse an index that starts at 0, len() to count items and append() to add one.
Grade 6
Find length, position, substrings and caseUse len(), find(), slicing such as word[1:4], upper() and lower().
Grade 7
Use a two-dimensional listAccess an item with name[row][column] and use nested loops to process every item.
Grade 8
Store and process records in a listHold each record as an inner list of fields and loop through the records to search or total them.
Quick recall
Cover the answers and test yourself. The app has these as flashcards that come back just before you'd forget them.
The program contains this line of code.
sold = input("Seats sold: ")
State the data type of the value stored in sold.
String
State the data type of the variable age after line 01 has run.
String
Complete the sentence. Changing a value from one data type to another, for example from a string to an integer, is called ____________.
casting
A weather program stores the average temperature for each of the 12 months of the year in a list called temps. State the index of the last item in temps.
11
Sample questions
Written for this site in the style of Edexcel exam questions. They are not taken from real past papers.
Question 1Easy4 marks
Look at this program.
01 age = input("Enter your age: ")
02 nextYear = int(age) + 1
03 print("Next year you will be " + str(nextYear))
(a) State the data type of the variable age after line 01 has run.
[1]
(b) Give a reason why int() is used in line 02.
[1]
(c) The user enters 14. State the output of the program.
[1]
(d) State what would happen if str() was removed from line 03.
[1]
Show the answer and mark scheme
(a)Answer: String
string / str
(b)Answer:input() returns a string, so the value in age must be converted to an integer before 1 can be added to it.
the input is a string / text, so it must be converted to an integer before arithmetic / adding 1 can be carried out
(c)Answer:Next year you will be 15
Next year you will be 15
(d)Answer: A runtime error (a TypeError) would occur, because a string cannot be joined to an integer with +.
a runtime error would occur / the program would crash (because a string and an integer cannot be concatenated with +)
Question 2Medium9 marks
A weather station records the maximum temperature, in °C, for each day of one week.
01 temps = [14, 17, 9, 21, 12, 18, 14]
02 total = 0
03 for t in temps:
04 total = total + t
05 mean = total / len(temps)
06 print(mean)
(a) State the output of the program.
[1]
(b) State the value of total after the loop has run three times.
[1]
(c) Write Python code, to be added to the end of the program, that counts how many of the temperatures are above the mean and then outputs the count.
[4]
(d) State the number of temperatures in the list that are above the mean.
[1]
(e) Explain why the temperatures are stored in a list rather than in seven separate variables.
[2]
Show the answer and mark scheme
(a)Answer:15.0
15.0
(b)Answer: 40 (14 + 17 + 9)
40
(c)Answer:
count = 0
for t in temps:
if t > mean:
count = count + 1
print(count)
sets a counter to 0 before the loop
loops through every temperature in the list
compares each temperature with mean using >
adds 1 to the counter when a temperature is above the mean
outputs the count after the loop has finished
(d)Answer: 3 (17, 21 and 18)
3
(e)Answer: All seven values are held under one identifier, so a loop can be used to process them, which makes the code shorter and means it still works if more days are added.
a loop can be used to process all the values / the code is shorter
only one identifier is needed / the related data is kept together
the program can easily be changed to work for more days / the list can be extended
Question 3Hard8 marks
A program stores people’s names as strings. Each name is made up of words separated by single spaces, for example "ada byron king".
(a) Write a Python function getInitials(name) that returns a string made up of the first letter of each word in name, in upper case. For example, getInitials("ada byron king") must return "ABK".
[5]
(b) State the value returned by getInitials("tim berners lee").
[1]
(c) A different programmer writes this version of the function.
01 def getInitials(name):
02 initials = ""
03 for i in range(len(name)):
04 if name[i] == " ":
05 initials = initials + name[i + 1]
06 print(initials)
Describe two problems with this version of the function.
[2]
Show the answer and mark scheme
(a)Answer:
def getInitials(name):
initials = name[0].upper()
for i in range(1, len(name)):
if name[i - 1] == " ":
initials = initials + name[i].upper()
return initials
a function header with one parameter, e.g. def getInitials(name):
includes the first character of the name (index 0)
loops through the characters of the name (or through the words, e.g. using split(" "))
identifies the first letter of every later word, e.g. the character after a space / word[0]
converts the initials to upper case using upper()
returns the string of initials (rather than printing it)
(b)Answer:TBL
TBL (must be in upper case)
(c)Answer: The first letter of the name is never added, because letters are only added after a space; the initials are not converted to upper case; and the initials are printed instead of being returned.
the first letter of the name / the initial of the first word is never added (only letters after a space are added)
the letters are not converted to upper case
it outputs the initials with print instead of returning them, so the calling code cannot use the value