6 - Programming
6 - Programming
6 - Programming
In this chapter there will be some example programs or sections of programs shown. All the programs have been
written using the parts of Python 3 that are specified in the Programming Language Subset (PLS) provided by
Edexcel.
When we create programs, we need to set different data types for the data that is input, processed and output
by our program. It is important that we set the right data type for the right data. This enables us to get the
correct input or output for our user. We need to be aware of the following data types:
Real These are numbers that can have a decimal part as well 0.1, 1.2, 3.4
Boolean This has two values only, true and false True/False, 1/0, Y/N
String This is used for text, and can include any character Computer Science is fun!
There may be a point in a program where we need to manually change the data type of an item of data that we
have stored. This is called casting. In Python, we need to change any data that we store to the string data type
if we want to output that data.
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 1 of 19 © ZigZag Education, 2021
EDEXCEL specification reference:
Understand the function of and be able to identify the structural components of programs (constants,
variables, initialisation and assignment statements, data structures, input/output)
Understand the need for and be able to follow and write programs that make appropriate use of one- and
two-dimensional structured data types (string, array, record)
Understand the need for and be able to follow and be able to write programs that make appropriate use of
variables and constants
Be able to write programs that accept and respond appropriately to user input
Understand the difference between and be able to write programs that make use of global and local variables
When we create a program, we will need to create a way for our user to input data into a program. We will also
need to create a way to store the input from our user, and a way to output any data we require to our user.
To store the data that is input into our program we will need to
create a data store. We can do this by using a variable, a constant,
a record or an array.
For example:
name = "me" The data stored in the variable. The quotation marks give it a string data type.
We can reassign the data that is stored in our variable at any point that is required in our program.
For example:
name = "Bob"
name = "Jane"
In this instance name will store ‘Bob’ until it is reassigned to store ‘Jane’.
We can give any name that we like to our data store, but we should choose the name carefully. The name must
be meaningful and relate to the data that is stored. We should also be careful to follow the conventions of the
programming language that we are using. For instance, you cannot have spaces in a variable name, as the
computer will not know how to read it properly!
The ability to choose meaningful variable names is something you will be assessed in the Paper 2 exam.
Any variables that are assigned in the subprograms are not recognised by the
program outside of it. This means that they are local variables.
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 2 of 19 © ZigZag Education, 2021
A constant is a data store that is also given a name. Where it differs from a variable is that a constant stores
data that will not be changed throughout the execution of the program. If we have a value that we need to use
repeatedly in a program, we could hardcode the value into the program each time we use it. Hardcoding the
value can cause two main problems, though:
1. It is bad practice to hardcode values into a program.
2. If we want to change the value, we would need to find all instances of it in order to change it.
If we use a constant to store the value, we can set it to the value we want to use throughout the program. Using a
constant throughout your program instead of hardcoding the value means you can change all of the values at once.
We store data in a constant in the same way that we store it in a variable, by assigning it to a constant name. It
is standard practice to use all capitals for the name of a constant.
For example:
PI = 3.1415
When we want to allow data to be input into our program, we need to create an input for our user.
For example:
name = input("Please enter the name of the student: ")
This will allow us to create a variable called ‘name’. It will then allow us to store whatever data the user inputs.
It also provides the user with a prompt of ‘Please enter the name of the student’.
When we want to output data to our user, we need to create an output for our data. For example:
print("Hello user! Welcome to my program")
This would output the message inside the quotation marks to the user. We can also output the contents that
are in a data store. For example:
name = "Jane"
print(name)
This would output the name ‘Jane’ to the user as the data ‘Jane’ is stored in the variable ‘name’.
An array is a data store that is designed to store a set of data that is all of the same data type. For example, a
list of the names of the students in your class could be stored in an array. Each item of data in an array is
called an element; each element can be accessed by referring to its position in the array. For example:
ClassList = ["Bob", "Jane", "Bill", "Annie", "Ali"]
If we want to reference an element of data in the list, we refer to the data location of the element. One thing
to note is that many programming languages label the first data location in an array as location 0. This means
that the data stored in element 3 of our class list array would be Annie.
We can change the value of an element in the array we write like this:
ClassList[1] = "John"
This replaces the value ‘Jane’ with ‘John’. This type of array is a called a one-dimensional array. We also need to
know about a second type of array called a two-dimensional array. If we think of a one-dimensional array as a
list of data that is stored, we can think of a two-dimensional array as a table of data that is stored. The reference
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 3 of 19 © ZigZag Education, 2021
to elements in this type of array has two parts. The first is like the row reference in a table and the second is like
the column reference in the table.
For example:
TestScores[3][5] = 85
This two-dimensional array will store three test scores for each of the five students in the class. For example:
Student Number
0 1 2 3 4
0 30 35 32 25 22
Test Score
1 29 21 29 25 28
2 27 23 32 26 19
We can create the array shown above using the following code:
TestScores = [[30,35,32,25,22],[29,21,29,25,28],[27,23,32,26,19]]
We can find out the test score stored for a student for a particular test by referring to the student number and
the test number. For example:
We write data to a two-dimensional array in the same way we write it to a one-dimensional array, by
referencing the element. For example:
TestScores[0][0] = 30 This writes the test score 30 to student 0 for test number 0
TestScores[2][3] = 26 This writes the test score 26 to student 3 for test number 2
Arrays are not supported in Python, it uses lists instead, which allow a group of values of different data types to
be stored under one identifier.
All the elements of an array must have the same data type, e.g. an array of ages, an array of city names.
A record, in contrast, will store different pieces of information (which can be stored as different data types)
about one person or thing. Once a record has been defined, it can be used many times for multiple people or
items.
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 4 of 19 © ZigZag Education, 2021
EDEXCEL specification reference:
Understand the function of and be able to identify the structural components of programs (command
sequences, selection, repetition, iteration)
Be able to follow and write programs that make appropriate use of:
sequencing selection repetition (count-controlled and condition-controlled) Iteration
There are four basic constructs that are the foundations of every program that we create; these are sequence,
selection, iteration and repetition:
Construct Description
Sequence The order in which the instructions need to occur in an algorithm is called a sequence. If the
instructions are not carried out in the correct sequence, a program may not have the desired output.
Therefore, we need to carefully consider the order in which instructions should occur when we
are designing an algorithm.
Selection Programs often needed to be coded in a way that allows it to follow
different paths. This is often dependent on a question and a condition.
The method for creating different paths in a program is called selection.
The path the program takes will depend on the answer to the question
and the condition.
Repetition Sometimes when we write a program, we will need to repeat instructions.
The repeating instructions is known as repetition.
We can put the instructions we would like to repeat inside a loop. We can
then set the loop to repeat a set number of times (a count-controlled loop)
or we can set the loop to repeat until a condition is met, or stops being met
(a condition-controlled loop).
Iteration When working with data structures we often need to cycle through each value stored within the
structure. Iteration is the process of using a loop to work through every item in a data structure.
An if–then–else statement allows us to check whether a condition is true or false and carry out a different
instruction depending on whether it is or not. They basically follow the logic that if x is true then do y, else do z.
For example:
if name == "me":
print("Hello me!")
else:
print("Who are you?")
This program will check if the data stored in the variable ‘name’ is equal to ‘me’.
If that is true it will output ‘Hello me!’; if it is false it will output ‘Who are you?’.
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 5 of 19 © ZigZag Education, 2021
If we have more than one condition that we want to check, we can use the command ‘elif’ in the statement.
For example:
if name == "me":
print("Hello me!")
elif name == "you":
print("Hello you!")
else:
print("who are you?")
Repetition is used to repeat instructions in a program. There are two types of repetition that we need to know:
for–to–next counting loops
while–endwhile condition loops
Discussion point: The code above will output the text ‘Hello world!’ five times, even though the loop has been
set to stop when n reaches 5. Why is this?
We should choose a counting loop when we want to repeat the instructions a set number of times. If we do not
know how many times, we want to repeat a set of instructions, chances are it will be until a condition is true or
false.
A while–endwhile loop allows us to repeat an instruction or a sequence of instructions until a condition is true
or false. This type of loop is controlled by a condition at the start of the loop. For example:
answer = "False"
while answer == "False":
print("Computer Science is the best subject")
answer = input("True or False? ")
This program will keep outputting the statement ‘Computer Science is the best subject’ until the user inputs
that this statement is true.
Iteration is used to work over each element in a data structure, for example an array.
A for loop can be used to iterate over every item in a list. For example:
This program will output the value of each item in the ClassList array.
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 6 of 19 © ZigZag Education, 2021
EDEXCEL specification reference:
Understand the need for and be able to write programs that use arithmetic operators:
add subtract divide multiply modulus integer division exponentiation
There are many arithmetic operators that we need to understand in order to effectively use them in programs:
+ Addition 1+2=3
– Subtraction 2–1=1
/ Division 6/3=2
* Multiplication 6 * 3 = 18
We can use arithmetic operators on integers and real numbers in our program. The rules of programming
follow the same rules as maths in terms of the order in which operators are carried out. They follow the rules
of BIDMAS.
!= Is not equal to – this can have a true or false outcome 1 != 1 would be False
< Is less than – this can have a true or false outcome 4 < 5 would be True
> Is greater than – this can have a true or false outcome 4 > 5 would be False
<= Is less than or equal to – this can have a true or false outcome 4 <= 4 would be True
>= Is greater than or equal to – this can have a true or false outcome 4 >= 5 would be False
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 7 of 19 © ZigZag Education, 2021
EDEXCEL specification reference:
Understand the need for and be able to write programs that use logical operators:
AND OR NOT
Be able to apply logical operators in truth tables with up to three inputs to solve problems
A condition can be True or False, e.g. ‘age > 17’ is a condition. Conditions are used in IF statements (selection)
and conditional loops (repetition).
Sometimes we need a combination of conditions. We can construct combinations using one of the following
three logical operators:
These are called complex conditions. Below are some examples showing how they can be used:
We can use truth tables to work out all the possible outcomes of a complex condition. We start by filling in all
the possible combinations of outcomes for each individual condition before working out the outcomes of the
combined conditions.
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 8 of 19 © ZigZag Education, 2021
Here is another example truth table for the complex condition:
Btn1 Btn2 Btn3 Btn1 and Btn2 (Btn1 or Btn2) and Btn3
FALSE FALSE FALSE FALSE FALSE
FALSE FALSE TRUE FALSE TRUE
FALSE TRUE FALSE FALSE FALSE
FALSE TRUE TRUE FALSE TRUE
TRUE FALSE FALSE FALSE FALSE
TRUE FALSE TRUE FALSE TRUE
TRUE TRUE FALSE TRUE TRUE
TRUE TRUE TRUE TRUE TRUE
A string is a list of characters. It can contain any type of character, including letters, numbers and symbols.
When we write a string in programs it is normally written inside single or double quotation marks. We have
been using double quotation marks.
When we are writing programs we can join together strings of data to form a
new string of data. This is called concatenation. We concatenate strings of
data together by using the + symbol.
For example:
greeting = "Hello"
name = "Bob"
question = "how are you?"
message = greeting + name + question
print(message)
This program stores three strings of data, ‘greeting’, ‘name’ and ‘question’. It then concatenates these three
strings together and stores this in the variable ‘message’. It then outputs the data that is stored in ‘message’.
At the moment there is a problem with the output; it would currently output the following:
HelloBobhow are you?
This is because we haven’t included a way to create spaces in between the strings of data that we have
concatenated together. To create spaces we need to add the following:
message = greeting + " " + name + " " + question
The inclusion of a space between quotation marks allows us to add spaces in between strings of data. The plus
(+) sign is used to add together each part that we want to concatenate, this includes for the space (" ") as well.
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 9 of 19 © ZigZag Education, 2021
There are a number of other actions we can perform on strings of data that we have stored. We will use the
variable name = "Bob" in our example. We are able to use the following commands:
len() This gives the number of characters that are in the string. len(name) 3
This will include any spaces.
.upper() This changes all the characters in the string to upper case. name.upper() "BOB"
.lower() This changes all the characters in the string to lower case. name.lower() "bob"
[x:y] This selects a particular part of a string. It starts at the place name[1:3] "ob"
in the string set by x and stops at the character before y.
We can make use of string manipulation in many ways. Have you ever noticed that shops always have codes for
all of the products they stock? They can use string manipulation to create these codes. For example:
This program creates a product code for each product by taking the first two characters of the colour of the
product, joins this to the first two characters of the type of the product and then joins the size. If we input the
colour Black, the type Trousers and the size 10, we would get the product code BlTr10.
When we create programs, we may find that we have sequences of instructions that we need to use on regular
occasions in our programs. We don’t use them repeatedly in a loop, but we do use the same instructions at
various points in our program. If we have sets of instructions that we use in this way, we can create a
subprogram to store them. We then just need to refer to the name we give to the subprogram, when we want
to use the particular set of instructions.
Using subprograms in our program can make our code neater and more efficient. They increase the reliability
of our code and can reduce the amount of code that we need to write.
When we create subprograms, we may need to pass data into our program. By this we mean the use of a value or
data in the subprogram we are creating. To do this we use parameters and arguments. A parameter is a type of
variable that is used to store the value. As with a normal type of variable, a parameter is given a name. It can also
be given a default value.
There are two types of subprograms that we can use: these are procedures and functions (covered on next page).
We can show this by using a subprogram called ‘greeting’.
greeting() This is the subprogram without a parameter
greeting(name) This is the subprogram with a parameter called name
greeting("Bob") This is the subprogram with the value ‘Bob’ passed to the parameter
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 10 of 19 © ZigZag Education, 2021
A procedure is a set of instructions that we can store and then use at any point we
want to in our program. We need to create our procedure, and then we can use it any
time we like by referring to the name we give it. We refer to this as ‘calling’ it.
For example:
def greeting():
print("Hello!")
print("Computer Science is so much fun!")
This is using the procedure without a parameter. We can add a parameter to the procedure to make our
message more personal. For example:
def greeting(name):
print("Hello" + name + "!")
print("Computer Science is so much fun!")
The parameter is passed the value ‘Bob’. When the procedure is called using greeting("Bob"), it will output:
Hello Bob!
Computer Science is so much fun!
This function has three parameters that are passed into the function. The output would be 19. The value
returned by a function must be stored in a variable or the value will be lost.
Note: functions do not have to be given parameters. For example, you may have a function that produces some
output, which never changes (like printing a specific phrase) – in this case, you may not need to pass a value to
this function.
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 11 of 19 © ZigZag Education, 2021
Most programming languages have built-in functions or library code
that can be used by a programmer to shorten the length of their code
and provide greater efficiency. Library code will have been pretested
too, so the programmer can be certain that it is correct.
File handling can be one of the trickier aspects of programming. It is when we take data that we have stored in
a variable or an array and store it in an external file. The most common type of external file that is used is .csv
(comma separated values) files. Each line in a .csv file consists of a list of comma separated values.
Open
Close
Read
Write
Putting data into a file is called writing data to a file. Using data from a file in a program is called reading data
from a file. In order to access an external file, we need to open it first. When we have finished reading data to
or writing data from an external file, we need to close it afterwards.
These are the steps we should follow when reading data to and writing data from a file:
To read from a file, we use an open command and follow this with a command to read from the file:
This will allow us to open a file called ‘test.txt’ and allow us to read data from the file.
We can then read each line from the file and output it:
If we want to write data to our file ‘test.txt’, we need to use the following code:
MyFile.writeline("Bob")
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 12 of 19 © ZigZag Education, 2021
When we have finished editing our file we need to close it using the command:
MyFile.close()
If we want to create a small program that will write the name ‘Bob’ to the file ‘test.txt’ we would use the following:
We may want to read all the lines of data from a file into a data structure. The following code will read each
line of data into the Lines data structure. It uses the .split() method to separate the values in each line into
individual elements:
names = []
for line in MyFile:
names.append(line)
If we wanted to create a program that read all the data from the file ‘test.txt’ into a data structure called
‘names’, we would use:
If we wanted to create a program that read all the data from a .csv file ‘students.csv’ into a data structure called
‘students’, we would use:
students = []
MyFile = open("students.csv", "r")
for student in MyFile:
students.append(student.split(","))
MyFile.close()
If we wanted to write the data from the ‘students’ data structure to the ‘students.csv’ file, we would use:
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 13 of 19 © ZigZag Education, 2021
This program does the following:
The program opens the file ‘students.csv’ where the data is to be stored. It opens it in write mode as
we want to write data from the program.
We then use a for loop that will keep carrying out the instructions inside the loop until it reaches the
end of the ‘students’ data structure.
The instructions it will carry out cause it to write one element from the data structure ‘students’.
Once the end of the file is reached, the program will stop looping.
We then close the file.
name = "Bob"
print("Hello " + naem)
This would cause the computer to advise us that we do not have a variable declared called ‘naem’.
An example of a logic error could be:
while n < 5:
n = 0
print(n)
n = n + 1
This would cause a logical error as it would create what is called an infinite loop. The variable n will never
reach 5 because each time the loop is run it is reset to 0. The declaration n = 0 should occur at the start of the
program, outside the loop.
A runtime error occurs while the program is running, leading to the program
crashing. These occur when the computer is being instructed to do something that
is not possible. The classic example is dividing by 0. Other examples are entering
text when the computer is expecting a number, or a real number is entered when
an integer was expected.
These errors may be caused by user input rather than an error in the actual
code. Code that uses validation to prevent this is desirable.
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 14 of 19 © ZigZag Education, 2021
EDEXCEL specification reference:
Be able to use logical reasoning and test data to evaluate a program’s fitness for purpose and efficiency
(number of compares, number of passes through a loop, use of memory)
Throughout the creation of our program, and also when we have finished,
we should be carrying out testing. When we test our program we are
checking that it does not contain any errors and that it works in the way
that we want it to. The more testing we can carry out on our program, the
less likely it is to break in the future due to a user encountering an error
that had not previously been discovered.
We should be testing our program while we are building it as well as
when we have finished building it. When we are testing our program
during the process of building it, this is called systematic testing. This is a
form of iterative testing, which is when we test our program and go back
and improve it as a result of the tests that have been carried out. If we
systematically test our program while we build it, we will find many of the
errors as we go along. This will mean we have fewer errors to find and correct at the end.
We also carry out testing after we have finished coding it and it appears functional. This type of testing is
called final or terminal testing. This type of testing is often aimed more at testing the functionality of the
system to find out whether it meets the requirements of the user that were laid out when a design was
developed for the program.
We must make sure testing is destructive. We must try to test with as much test data as we can to try to break
our program. This will mean
not just entering the data that an input should accept, but testing that it does not accept any other kind of data
that we do not want it to accept.
For example, let’s consider the following input:
age = int(input("Age: "))
We have created an input that accepts only integer data. We will want to test whether the input accepts data
that is of the data type integer. But we will also need to check that the input rejects real data types or any
string data types. Therefore, we may test it with the following data:
This selection of data thoroughly tests our input, making sure that it should only accept data that is an integer.
We have recorded our testing in a testing table. We should make sure that we thoroughly test our programs
with data that should be accepted and also rejected by the program. We also need to test the logic of our
programs and test to see whether the design requirements have been met.
We have used two main types of test data in our testing table: normal and erroneous test data. There is a third
type of test data called boundary (or extreme) test data. This would have to be added to the table if there was
an age range set (e.g. only users aged 18 or over).
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 15 of 19 © ZigZag Education, 2021
Test No. Test description Test data Type Expected outcome
Testing the input for the age variable accepts
4 18 Boundary Data will be accepted
an input on the boundary of 18
Normal test data refers to data that the program should process normally, data that it should accept.
Erroneous data refers to data that the program should not accept, data that it should reject.
Boundary data refers to data that will fall on the edge of any acceptable ranges or limits that have been set.
Multiple programs can perform the same job, however some of them may be more efficient than others. We can
measure the efficiency of a program in two main ways:
Time – the number of steps the program goes through
Space/Memory Usage - the amount of memory the program uses during execution
When considering the time efficiency of a program, we don’t measure the number of seconds it takes to
execute. Instead we look at how many steps the program goes through during execution.
Programs A and B below both find and output the largest value in the ‘scores’ list, however, they are different in
their time efficiency. In Program A the length of the list is calculated at the start of every iteration. Whereas in
Program B the length is calculated once before the loop starts. This means that Program A has to perform an
additional step in each iteration, making Program B more time efficient.
Program A Program B
scores = [45,21,98,28,62,85] scores = [45,21,98,28,62,85]
index = 0 index = 0
largest = 0 largest = 0
while index < len(scores): length = len(scores)
if scores[index] > largest: while index < length:
largest = scores[index] if scores[index] > largest:
index = index + 1 largest = scores[index]
print(largest) index = index + 1
print(largest)
When testing a program for logic errors, we need a method of working out what
the correct output should be for different inputs. One method is using a trace
table. Each column holds the values for a variable and each row represents a
different iteration of the code. This will allow the tester to locate the point at
which an error occurs and fix the code.
y = 4 x y output
for x in range(1,6): 4
y = y + x 1 5
print(y)
2 7
3 10
4 14
5 19 19
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 16 of 19 © ZigZag Education, 2021
EDEXCEL specification reference:
Be able to use techniques (layout, indentation, comments, meaningful identifiers, white space) to make
programs easier to read, understand and maintain
It is very important, when we create code, to make sure that our code is maintainable. This means that when we
look at the code again after a period of time, or someone else wants to use the code at a later point in time, it
is clear to follow the code and understand how it has been structured.
There are three things that we can do to make sure our code is maintainable and easy to understand and use in
the future: these are (1) adding comments to our code, (2) laying out our code appropriately and (3) using
meaningful identifiers.
When we add comments to our code, we describe what the different parts of our code are doing. We will add
comments to describe how a certain section, such as an iteration, selection or sub-procedure is working.
We add comments in Python using a hash ( # ) followed by our description. For example:
By adding comments to our code, this means that when we look at it again in the future, or someone else wants
to use our code, we can read the comments and follow the structure of how the program has been created.
We can also ensure the layout of our code makes it easier to read and understand. We can achieve this by using
indentation and by placing white space between blocks of code. Some programming languages insist on us
indenting sections to show what instruction should occur, for example inside a loop or selection; others do not
insist on this, but we should still do it. By indenting our code, it makes it easier for us to see what instructions
are meant to be executed inside the loop or as a result of a condition in a selection.
It is also important to choose meaningful identifiers when naming variables, constants and subprograms. This
ensures that it is easy to understand their purpose at a glance. Where possible we should avoid single letter
variable names. An exception to this rule is the naming of counters used in count-controlled loops.
Programs should always be designed to be as user-friendly and as secure as possible. We want our program to
be unbreakable and for no errors to occur when it is used. In order to achieve this, we need to try to anticipate
what errors our user might make. Thinking about designing our program in this way is called defensive design.
One of the main areas in which a user may make a mistake is in the data that they are required to input into a
program. They may enter the wrong data accidentally, by mistyping, or they may misunderstand the data they
are required to enter and enter the wrong type of data. To stop errors from occurring in this way we can do
three things: we can create clear and instructive prompts for our user interface that clearly tell our user what
data we want them to input, we can validate the inputs they give, and we can also remove any unwanted data
from the input, sanitising it. For example, an input might not allow numbers in it, so you could write a function
that sanitises the data by removing all digits from the input.
When we use input sanitisation on a user’s input, we remove any data that we do not want. This is often done
by anticipating what kind of incorrect data a user may input, storing it in a list, and asking the program to check
the list to remove any of the data it finds that matches the list.
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 17 of 19 © ZigZag Education, 2021
When we use validation on our inputs, we create rules that the input must follow
to be acceptable. Below are some common validation rules that we can use:
By limiting or checking the data our user enters, this can make the data more reliable and stop errors occurring
in our program. The code below is an example of a length check. It asks the user to input a telephone number
and checks that it is 11 digits in length:
The code below is an example of a range check. It asks the user to input their age and checks whether they are
15 or over:
age = int(input("Age: "))
while age < 15:
print("You are too young, please re-enter")
age = int(input("Age: "))
print("Age accepted")
The code below is an example of a pattern check. It asks the user to enter an ID number and checks that it
starts with ‘PRO’ followed by two numbers.
idNum = input("ID: ")
while idNum[0:3] == "PRO" and idNum[3:5].isdigit():
print("ID invalid, please re-enter")
idNum = input("ID: ")
print("ID accepted")
The code below is an example of a presence check. It asks the user to enter their name and whether it contains
at least one character.
name = input("Name: ")
while len(name) == 0:
print("You must enter a name.")
name = input("Name: ")
print("Name accepted")
It is often necessary to check the identity of the user before allowing them access to a program, this is known
as authentication. The example code below asks the user to input their password and checks whether it is equal
to ‘computing’.
pw = input("Password: ")
while pw != "computing":
print("Password incorrect.")
pw = input("Password: ")
print("Password accepted")
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 18 of 19 © ZigZag Education, 2021
i
?
There are four main programming constructs: sequence, selection, repetition and iteration.
When we write a program we need to apply data types to the data that it handles. There are five main
data types: integer, real, Boolean, character and string.
We store data in various ways in a program, including variables, constants and arrays.
Arrays can be be one-dimensional or two-dimensional.
We may need to store data externally to a program; we do this using an external file. We need to be able
to open and close the file to use it, and to also read and write data to and from the file.
We may need to manipulate the strings of data that we store in a program, extracting sections from them
and joining strings together.
We can store sections of instructions that we may want to use in a program in a subprogram. There are
two main types of subprogram: a function and a procedure.
There are three main types of error that can occur when we are writing programs: syntax errors, logical
errors and runtime errors.
We need to make sure when we write our code that we make it maintainable. We can do this in a variety
of ways, including adding comments and using meaningful identifier names.
We need to make sure that we thoroughly test the programs that we create.
We can use a trace table to work out the values assigned to variables at each stage in a program.
The logical operators AND, OR and NOT can be used to create even more complex conditions.
Library code is procedures and functions pre-created and tested that are available to the programmer.
Validation can be used to check that user inputs meet certain rules.
Authentication can be used to check the identity of a user before allowing them access to the program.
?
1. Describe what is meant by the term ‘selection’. [2]
2. What type of error would most likely occur if some code were missing a colon or double quote? [1]
3. Explain two techniques a programmer can use to make a program more robust. [4]
4. A hospital wants a program that records and monitors the temperature of each baby that is currently in its
maternity unit. It wants to store the temperature of each baby; it will have 15 babies in the unit at a time.
If a baby’s temperature is below 36.5 degrees, the program should alert a nurse with a suitable message.
If a baby’s temperature is above 37.5 degrees, the program should alert a nurse with a suitable message.
Describe a simple program that the hospital could use to store and monitor the temperatures of the
babies in the unit. [6]
5. If only users with 10 or more points can proceed to the next level, give examples of normal, boundary and
erroneous data. [3]
6. Name the data type that has two possible values of true and false. [1]
7. Consider the following: x = 10 % 4
What is the value of x? [1]
8. What would the following code output to the screen? [1]
name = "Dave"
print(name[0:2])
9. What is the difference between a procedure and a function? [1]
GCSE Edexcel Computer Science (1CP2) Course Companion Topic 6 Page 19 of 19 © ZigZag Education, 2021