Variables, constants and data structures (strings, arrays and records)

GCSE Computer Science (Edexcel) · Edexcel 1CP2 · 1.2.2 · Computational thinking › Algorithms

75 exam-style questions 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.

Revision notes

Programs store data in variables and constants, and group data into data structures: strings, one- and two-dimensional arrays, and records. Questions ask you to define these terms, state the value stored at a given index, explain why a constant is used, and write code that works with arrays and records.

Key facts

  • Variable: a named memory location whose value can change while the program runs
  • Constant: a named value that stays the same while the program runs (Python convention: CAPITALS)
  • String: a sequence of characters; the first character has index 0
  • len() gives the number of characters in a string or items in a list
  • Array: many items of the same data type under one identifier, accessed by an index from 0
  • 2D array: rows and columns, table[row][column]
  • Record: related fields about one item; the fields can be different data types
  • Last index = length − 1

Notes

Variables and constants

  • A variable is a named location in memory that holds a value that can change while the program runs.
  • In score = score + 10 the right-hand side is worked out first, then the result is stored in score.
  • A constant is a named value that does not change while the program runs. Python has no true constants, so by convention they are written in capitals and never reassigned, e.g. VAT_RATE = 0.2.
  • Benefits of a constant: if the value ever needs updating it is changed in one place only, and the name is easier to understand than a bare number. In languages that enforce constants, the value also cannot be changed by mistake while the program runs.
  • Use meaningful identifiers, such as totalCost rather than x.

Strings

  • A string is a sequence of characters in quotation marks. Each character has an index, starting at 0.
  • This outputs P, then 6, then PYTHON3.
    word = "PYTHON"
    print(word[0])
    print(len(word))
    print(word + "3")
  • To join a number to a string, convert it first: "Score: " + str(score).

Arrays

diagram
  • An array stores many items of the same type under one identifier. Each item is found by its index, starting at 0. In Python, arrays are written as lists.
  • One-dimensional: in scores = [12, 7, 19, 4], scores[2] is 19 and scores[1] = 8 changes the second item. The last index is len(scores) - 1.
  • scores1271940123indexscores[2] is 19
    Each item has an index, starting at 0. The last index is len(scores) − 1 = 3
  • col 0col 1col 2row 0row 1582369sales[1][2] is 9: row first, then column
    A 2D array is a table: the first index picks the row, the second picks the column
  • Two-dimensional: a table of rows and columns, written as a list of lists. The first index picks the row and the second picks the column. This outputs 9 (row 1, column 2).
    sales = [[5, 8, 2],
             [3, 6, 9]]
    print(sales[1][2])

Records

  • A record groups the related data items (fields) about one thing. The fields can be different data types.
  • In Python a record can be stored as a list: in pupil = ["P104", "Amira", 15], pupil[1] is the name field.
  • A table of records is a two-dimensional structure (a list of records): pupils[0][1] is the name of the first pupil.
  • Array or record? An array holds many items of the same type (e.g. 30 test scores); a record keeps different types of data about one item together.

How to answer each type of question

State the difference between a variable and a constant

1 markGrade 3
  1. Say what happens to the value while the program is running.
  2. Variable: the value can change. Constant: the value stays the same.

Example. State one difference between a variable and a constant.

Show the model answerHide the model answer
The value of a variable can change while the program is running, but the value of a constant cannot (1).

State the value stored in a data structure

1 mark eachGrade 5
  1. Count indexes from 0.
  2. For a two-dimensional array, find the row first, then the column.
  3. Give the value exactly as it is stored.

Example. Here is a two-dimensional list.

stock = [["pen", 40, 0.5],
         ["ruler", 12, 1.2],
         ["glue", 5, 2.75]]
State the value of:
(a) stock[1][0]
(b) stock[2][1]
(c) len(stock)

Show the model answerHide the model answer
(a) ruler
(1)
(b) 5
(1)
(c) 3 (1), because there are three records

Explain why a constant is used

2 marksGrade 5
  1. Give a benefit: the value is set in one place only, or the name explains what the value means.
  2. Add the consequence, linked to the program in the question.

Example. A program for a shop uses the constant VAT_RATE = 0.2 in several calculations.
Explain one benefit of using a constant for the VAT rate.

Show the model answerHide the model answer
If the VAT rate changes, the programmer only needs to change the value in one place (1), so every calculation that uses it is updated and none are missed
(1).
Or: the name VAT_RATE shows what the number means (1), so the code is easier to read and maintain
(1).

Choose a suitable data structure

2 marksGrade 7
  1. Say what the data is like: one item or many, the same type or mixed types.
  2. Link this to a feature of the structure: a record holds fields of different types about one item; an array holds many items of one type.

Example. A program stores the title, the year of release and the star rating (such as 4.5) of one film.
Explain why a record is a suitable data structure for this data.

Show the model answerHide the model answer
The data items are all about one film, so a record keeps them together (1). They are different data types (a string, an integer and a real number), and the fields of a record can be different types (1).

Write code that processes a list of records

3 to 6 marksGrade 8
  1. Loop through every record in the list.
  2. Pick out the field you need using its index.
  3. Apply the condition or calculation, then output the correct field.

Example. Here is a two-dimensional list. Each record holds an item's name, the number in stock and the price.

stock = [["pen", 40, 0.5],
         ["ruler", 12, 1.2],
         ["glue", 5, 2.75]]
Write Python code that outputs the name of every item that has fewer than 20 in stock.

Show the model answerHide the model answer
for item in stock:
    if item[1] < 20:
        print(item[0])
Loops through every record (1); uses the number in stock, index 1 (1); a correct comparison, less than 20 (1); outputs the name field, index 0
(1).
For this list the output is ruler, then glue.

Don’t lose marks

  • Counting indexes from 1 instead of 0.
  • Swapping the row and the column in a two-dimensional array.
  • Saying a constant can never be changed. The programmer can edit it in the code; it just does not change while the program runs.
  • Joining a number to a string with + without using str() first.
  • Using an index equal to the length of the list, e.g. scores[4] for a list of 4 items. This causes an 'index out of range' runtime error.

More tips

Memory tricks

  • Row first, then column: grid[row][column]. Go down to the row, then across.
  • Indexes start at 0: the 5th item is [4] and the last item is at length − 1.
  • CAPITALS say 'constant: do not change me'.
  • Record = one row of a table (one thing). Field = one column (one piece of data about it).

Exam technique

  • When you state a value from a two-dimensional array, check it by saying 'row ..., column ...' to yourself.
  • In 'explain' questions about constants, link your answer to the value in the question, such as a tax rate or a maximum score.
  • When writing code, use exactly the identifiers and field positions given in the question.

What each grade needs

What you need to be able to do, from the first marks up to the top grade.

  1. Grade 3
    Define variable and constantA variable's value can change while the program runs; a constant's value does not.
  2. Grade 4
    Access an array item by its indexIndexes start at 0, so scores[2] is the third item.
  3. Grade 5
    Explain the benefits of using constantsThe value is changed in one place only, and the name makes the code easier to read.
  4. Grade 5
    Use string length, indexing and concatenationUse len(), word[0] and + to work with strings.
  5. Grade 6
    Use a two-dimensional arrayFind or change an item using a row index and then a column index.
  6. Grade 7
    Choose between an array and a recordA record holds related fields of different types; an array holds items of the same type.
  7. Grade 8
    Process arrays and records with loopsLoop through every item or record to total, count, search or output fields.

Quick recall

Cover the answers and test yourself. The app has these as flashcards that come back just before you'd forget them.

Define the term 'variable'.
A named memory location holding a value that can change while the program runs.
This program works out the total price of an item including VAT.
01 VAT_RATE = 0.2
02 price = float(input("Enter the price: "))
03 vat = price * VAT_RATE
04 total = price + vat
05 print("Total:", total)
Identify the constant in the program.
VAT_RATE
A music app stores the songs in a playlist in a one-dimensional array. In Python, the array is a list. The first item has index 0.
playlist = ["Sunrise", "Echoes", "Paper Planes",
            "Tidal", "Neon Lights"]
State the output of print(playlist[2]).
Paper Planes
An online shop uses this program to work out the total cost of an order. By convention, the identifiers of constants are written in capital letters.
01 VAT_RATE = 0.2
02 DELIVERY = 4.99
03 cost = float(input("Cost of goods: "))
04 vat = cost * VAT_RATE
05 total = cost + vat + DELIVERY
06 print("Total to pay:", round(total, 2))
Identify one constant used in the program.
VAT_RATE or DELIVERY
A café program contains this line: is_open = False
State the data type of the value False.
Boolean
State the name of the Python function that returns the number of characters in a string.
len()

Sample questions

Written for this site in the style of Edexcel exam questions. They are not taken from real past papers.

Question 1Easy3 marks
(a) Define the term 'variable'.
[1]
(b) State one difference between a variable and a constant.
[1]
(c) Identify the data structure that holds a number of items of the same data type, each accessed using an index.
[1]
  • Array
  • Record
  • Constant
  • Boolean
Show the answer and mark scheme
(a) Answer: A named memory location holding a value that can change while the program runs.
  • a named location in memory that stores a value, which can change while the program is running
(b) Answer: A constant's value stays the same while the program runs; a variable's value can change.
  • the value of a constant cannot change while the program is running, whereas the value of a variable can change
(c) Answer: Array
Question 2Medium4 marks
This program works out the total price of an item including VAT.
01 VAT_RATE = 0.2
02 price = float(input("Enter the price: "))
03 vat = price * VAT_RATE
04 total = price + vat
05 print("Total:", total)
(a) Identify the constant in the program.
[1]
(b) Identify one variable in the program.
[1]
(c) Explain one benefit of using a constant for the VAT rate instead of writing 0.2 wherever it is needed.
[2]
Show the answer and mark scheme
(a) Answer: VAT_RATE
  • VAT_RATE
(b) Answer: price
  • price / vat / total
(c) Answer: If the rate changes, only line 01 needs editing, so no occurrence of 0.2 can be missed (and the name makes the code clearer).
  • if the VAT rate changes, it only has to be changed in one place (line 01) / the meaningful name shows what the value is
  • so every part of the program uses the new value and none is missed / so the code is easier to read and maintain
Question 3Hard6 marks
A sports club stores details of its 200 members: each member’s name, membership number, date of joining and whether they have paid this year’s fee.
(a) Describe how the club could use records and an array to store these details.
[4]
(b) Explain why storing the details in four separate arrays, one for each item, could cause problems.
[2]
Show the answer and mark scheme
(a) Answer: One record per member with a field for each detail (string, integer, date, Boolean), and an array of 200 of these records that a loop can process.
  • each member’s details are stored in one record
  • with one field for each item: name (string), membership number (integer), date of joining (string / date) and paid (Boolean)
  • the 200 records are stored in an array, one element for each member
  • so a loop can go through the array to process every member, e.g. to list the members who have not paid
  • each field is accessed by its name (or its position in the record), so the details of one member stay together
(b) Answer: A member’s details are linked only by their index, so changing or sorting one array but not the others mixes up different members’ details.
  • the details of one member are spread across four arrays and are only linked by being at the same index
  • if one array is sorted, or has an item added or removed, without the others being changed in the same way, the details become mismatched (they belong to the wrong member)

More in Algorithms

Stuck? Get 1-to-1 help.

Chhetri Academy tutors GCSE and A level Maths and Science online, with a free 30-minute trial lesson.