40 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: 12 questions on this subtopic in GCSE Computer Science (Edexcel), marked as you tap.
Writing code that works and that other people can follow: making programs readable, finding and fixing syntax, logic and runtime errors, validating input, authenticating users, and testing with normal, boundary and erroneous data. It is central to Paper 2, the onscreen programming exam, where you correct, improve and test Python code.
Key facts
Syntax error: breaks the rules of the language, so the program will not run
Logic error: the program runs but gives the wrong result
Runtime error: the program crashes while running, e.g. division by zero
Readability: comments, meaningful identifiers, indentation, white space
Validation checks data is sensible; it cannot prove data is correct
Authentication: confirming a user's identity, e.g. looking up an ID and checking its password
Normal data: valid, accepted. Boundary data: on the edge of the range, accepted. Erroneous data: invalid, rejected
Efficiency: number of comparisons, passes through loops, memory used
Decomposition: break a problem into parts. Abstraction: remove unnecessary detail
Notes
Readable code
Comments (after #) explain what the code does. Python ignores them.
Meaningful identifiers, e.g. totalCost not t, show what each variable or subprogram is for.
Indentation shows which lines are inside an if, a loop or a subprogram. In Python it is part of the syntax.
White space: blank lines between sections and spaces around operators. Readable code is quicker to debug and maintain.
Three types of error
Syntax error: the code breaks the rules of the language, so it cannot be translated and will not run, e.g. a missing colon, bracket or quotation mark.
Logic error: the program runs but gives the wrong result, e.g. > instead of >=.
Runtime error: the program crashes while running, e.g. dividing by zero, int("ten") or an index that is not in the list.
Find logic errors with a trace table, or with temporary print() lines that show the values of variables.
Validation and authentication
Validation checks that input is sensible and allowed before it is used. It cannot prove data is correct: 41 is a valid age even if the user is 14.
Presence check: something was entered. Length check: an allowed number of characters. Range check: a value between limits. Pattern check (format check): the right form, e.g. two letters then four digits.
Authentication confirms that users are who they say they are: look up the user's ID in the stored data and check that the password stored with it matches.
Testing and evaluating
diagram
Normal data: valid values inside the range, e.g. 23 for a mark from 0 to 50. They should be accepted.
Boundary data: valid values on the edges of the range (0 and 50). Also test just outside (−1 and 51): these must be rejected.
Erroneous data: invalid data that should be rejected, e.g. 75 or ten.
Test data for a mark from 0 to 50 (the axis is broken between the ends).
A test plan lists each test's data, type and expected result. A program is fit for purpose if it meets all of its requirements.
Judge efficiency by the number of comparisons, passes through loops and memory used. A search that stops when it finds the item usually makes fewer passes than one that checks every item. Grade 8+ only
From problem to program
Decomposition: split the problem into parts, e.g. one subprogram per task. Abstraction: keep only the details the program needs.
Convert a flowchart or pseudocode step by step: inputs become input(), processes become assignments, decisions become if statements or loop conditions, outputs become print().
Refine after testing: fix errors and replace repeated code with a loop or subprogram.
How to answer each type of question
Identify the validation check
1 mark eachGrade 4
Look at what the condition tests: whether anything was entered, the number of characters, the size of a number, or the form of the data.
Name the check exactly: presence, length, range or pattern.
Example. Each line of code below is the start of a validation check.
01 if username == "":
02 if len(postcode) < 6 or len(postcode) > 8:
03 if quantity < 1 or quantity > 20:
04 if not phone.isdigit():
State the type of validation check carried out on each line. (4)Show the model answerHide the model answer
01: presence check
(1)
02: length check
(1)
03: range check
(1)
04: pattern check: only digits are allowed
(1)
Give ways to improve readability
2 to 4 marksGrade 4
Choose techniques that fit the code you are given: comments, meaningful identifiers, indentation, white space.
Link each technique to this program, e.g. name the variable you would rename.
Explain how it helps a programmer who reads or maintains the code.
Example. This program works out the cost of a meal, including a 10% service charge. It works, but it is hard to read.
a=float(input("?"))
b=a*0.1
print(a+b)
Give two ways to make this program easier to read. Explain how each way helps a programmer. (4)Show the model answerHide the model answer
Use meaningful identifiers, e.g. mealCost and serviceCharge instead of a and b (1), so it is clear what each variable stores
(1).
Add a comment such as # add a 10% service charge (1), which explains the purpose of the calculation to anyone maintaining the code
(1).
Also accept white space, e.g. spaces around = and *, with a matching explanation.
Complete a test plan
3 to 6 marksGrade 5
Find the valid range or rule in the question.
Normal: a value well inside the range. Boundary: a value exactly on a limit. Erroneous: a value that breaks the rule.
Give an actual value, not a description, and state exactly what should happen: accepted, or rejected with a message.
Example. A program asks how many tickets a customer wants. Valid values are whole numbers from 1 to 6 inclusive. Complete the test plan by giving test data and the expected result for each type of test. (3)
Type of test
Test data
Expected result
Normal
Boundary
Erroneous
Show the model answerHide the model answer
Type of test
Test data
Expected result
Normal
e.g. 3
Accepted (1)
Boundary
1 or 6
Accepted (1)
Erroneous
e.g. 9, 0 or two
Rejected with an error message (1)
Each mark needs both the test data and the correct expected result.
Identify and correct errors in code
2 to 4 marksGrade 6
Read what the program should do, then read the code line by line.
Look for syntax errors first: missing colons, brackets or quotation marks, and wrong indentation.
Trace the code with simple test values to find logic errors: compare what it does with what it should do.
Give the line number, name the type of error and write out the whole corrected line.
Example. This program should input three marks and output their mean. It contains one syntax error and one logic error.
01 total = 0
02 for count in range(3)
03 mark = int(input("Enter a mark: "))
04 total = total + mark
05 mean = total / 2
06 print("Mean:", mean)
(a) Give the line number of the syntax error and write the corrected line. (2) (b) Give the line number of the logic error and write the corrected line. (2)Show the model answerHide the model answer
(a) Line 02 (1): for count in range(3):
(1)
(b) Line 05 (1): mean = total / 3
(1)
Explain which program is more efficient
2 to 4 marksGrade 8
Count what each program does: comparisons made, passes through each loop, and extra variables or lists stored.
Say which program is more efficient.
Explain why, comparing the two programs directly (use 'whereas').
Example. Both programs set found to True if target is in the list names, which holds 500 names. Program A
found = False
for name in names:
if name == target:
found = True
Program B
found = False
index = 0
while found == False and index < len(names):
if names[index] == target:
found = True
index = index + 1
Explain which program is more efficient. (3)Show the model answerHide the model answer
Program B (1). It stops looping as soon as the target is found (1), whereas Program A always makes 500 passes through the loop and 500 comparisons, even when the target is the first name
(1).
(If the target is not in the list, both programs make 500 passes.)
Don’t lose marks
Saying validation makes sure data is correct. It only checks that data is reasonable and follows the rules.
Choosing boundary data from the middle of the range. Boundary values sit exactly on the limits.
Calling a crash a logic error. A program that stops part-way with an error message has a runtime error.
Writing a description such as 'a big number' in a test plan instead of an actual value such as 51.
Correcting one error but also changing other lines, e.g. their indentation, which adds a new error.
Saying comments make a program run better. They are ignored when the program runs and only help people.
More tips
Memory tricks
Syntax stops it starting, runtime stops it running, logic lets it finish with the wrong answer.
Validation checks in four questions: is it there (presence)? Is it the right size (length)? Is it within the limits (range)? Is it the right shape (pattern)?
Boundary tests for a whole-number range from a to b: test a and b (accepted), then a − 1 and b + 1 (rejected).
Readability checklist: comments, identifiers, indentation, white space.
Validation asks 'is this data reasonable?'; authentication asks 'is this really you?'
Exam technique
For 'identify the error', give the line number and the type of error; for 'correct the error', write out the whole corrected line.
State expected results precisely, e.g. 'rejected, error message shown and asked again', not 'it works'.
In the onscreen exam, run your program after every change and test it with normal, boundary and erroneous data.
When improving readability, do not change what the program does, and rename a variable everywhere it appears.
Use the exact terms: syntax, logic, runtime; presence, length, range, pattern; normal, boundary, erroneous.
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 three types of program errorSyntax, logic and runtime errors, with an example of each.
Grade 4
Make code easier to read and maintainAdd comments, meaningful identifiers, indentation and white space without changing what the program does.
Grade 4
Identify presence, length, range and pattern checksSay which validation check a line of code carries out and why it is needed.
Grade 5
Choose normal, boundary and erroneous test dataPick actual values for a test plan and give the expected result of each test.
Grade 6
Locate and correct errors in a programFind the line with the error, name the type of error and write the corrected line.
Grade 6
Convert a flowchart or pseudocode into PythonTurn each input, process, decision and output of an algorithm into the matching Python statement.
Grade 7
Write validation and authentication codeRepeat an input until it passes every check, and check an ID and password against stored data.
Grade 8
Evaluate fitness for purpose and efficiencyUse test results and the number of comparisons, loop passes and memory used to judge a program.
Quick recall
Cover the answers and test yourself. The app has these as flashcards that come back just before you'd forget them.
Students log in to an online homework website with a username and a password. State the purpose of authentication.
To check that a user is who they claim to be before they are allowed access.
State the type of error that stops a program from being translated and run.
Syntax error
State the type of validation check that your while loop carries out.
A range check.
Name the type of error that stops this program while it is running.
Runtime error
Give one reason why the programmer tests the program with erroneous (invalid) data.
To check that the program rejects invalid data and does not crash or accept it.
Sample questions
Written for this site in the style of Edexcel exam questions. They are not taken from real past papers.
Question 1Easy6 marks
Programmers use several techniques to make their code easier to read, understand and maintain.
(a) Give three techniques that make program code easier to read.
[3]
(b) Identify the change that would not make a program easier to read.
[1]
Adding comments to explain each section of code
Using the identifier totalCost instead of tc
Writing as many statements as possible on each line
Leaving a blank line between sections of code
(c) A programmer needs to change a program that was written by someone else a year ago. Explain one way in which comments in the code would help the programmer.
[2]
Show the answer and mark scheme
(a)Answer: For example: comments, meaningful (descriptive) identifiers and indentation.
comments (to explain what the code does)
meaningful / descriptive identifiers (for variables and subprograms)
indentation (to show the structure of loops, selection and subprograms)
white space / blank lines between sections of code
a consistent layout, e.g. one statement on each line
(b)Answer: Writing as many statements as possible on each line
(c)Answer: Comments explain what each part of the code does, so the programmer can quickly find and understand the part that needs changing without working it out line by line.
comments explain the purpose of sections / lines of code
so the programmer can find / understand the code that needs changing more quickly / is less likely to introduce errors
Question 2Medium10 marks
This program works correctly, but it is difficult to read.
01 a=0
02 b=0
03 for c in range(5):
04 d=int(input("?"))
05 if d>=40:
06 a=a+1
07 b=b+d
08 print(a,b/5)
(a) Describe the purpose of the program.
[2]
(b) Give two ways in which the program could be made easier to read. For each way, give an example from this program.
[4]
(c) Amend the program so that it is easier to read. It must still work in exactly the same way.
[4]
Show the answer and mark scheme
(a)Answer: It inputs five marks, counts how many of them are 40 or more, and outputs this count and the mean of the five marks.
counts how many of the five values entered are 40 or more (e.g. passes)
outputs this count and the mean / average of the five values
(b)Answer: Use meaningful identifiers, e.g. passes and total instead of a and b. Add comments, e.g. to explain that 40 is the pass mark.
use meaningful identifiers
e.g. passes / total / mark instead of a / b / d
add comments
e.g. to explain that the loop inputs five marks / that 40 is the pass mark
add white space
e.g. spaces around = and >= / a blank line before the print statement
use a named constant
e.g. NUMBER_OF_MARKS = 5 instead of writing 5 in two places
(c)Answer:
# Count the passes and find the mean of five test marks
passes = 0
total = 0
for count in range(5):
mark = int(input("Enter a mark: "))
# A mark of 40 or more is a pass
if mark >= 40:
passes = passes + 1
total = total + mark
# Output the number of passes and the mean mark
print(passes, total / 5)
meaningful identifiers for all four variables
at least two sensible comments
white space, e.g. spaces around operators and blank lines between sections
the logic is unchanged: same loop, condition, calculations and output
Question 3Hard9 marks
A computer club stores its members’ usernames and passwords in two lists. The password for each username is at the same index in the list passwords.
checks whether the username is in the list and the password is the one stored at the same index
gives the user a maximum of three attempts
outputs Access granted as soon as correct details are entered, or Account locked after three failed attempts.
You should add to the two lines of code above.
[7]
(b) Explain why the program should not tell the user whether it was the username or the password that was wrong.
[2]
Show the answer and mark scheme
(a)Answer:
usernames = ["akhan", "bjones", "cwu"]
passwords = ["Tiger#81", "sunset22", "Qx7!pond"]
attempts = 0
granted = False
while attempts < 3 and not granted:
user = input("Username: ")
word = input("Password: ")
for index in range(len(usernames)):
if usernames[index] == user and passwords[index] == word:
granted = True
attempts = attempts + 1
if granted:
print("Access granted")
else:
print("Account locked")
a loop that allows at most three attempts (with the attempts counted)
the loop stops as soon as correct details are entered (e.g. a flag in the condition)
inputs a username and a password on each attempt
checks every username in the list
compares the password with the one at the same index as the matching username
access is only granted when both the username and the password match
outputs Access granted when the details are correct
outputs Account locked after three failed attempts (and not otherwise)
(b)Answer: It would tell someone trying to break in that the username exists, so they would only need to guess the password.
it would tell an attacker that the username exists / is valid
so they would only need to guess the password (making unauthorised access easier)