0% found this document useful (0 votes)
9 views

6 - Programming

Chapter 6 of 'The Ultimate GCSE CS Textbook for Edexcel' covers programming concepts including subprograms, data types, operators, and programming errors. It utilizes the PRIMM approach for teaching and includes Python examples with links to code files for practical application. The chapter emphasizes the importance of teaching programming concepts in a flexible order and provides various activities and exercises for students to engage with the material.

Uploaded by

smarinelli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

6 - Programming

Chapter 6 of 'The Ultimate GCSE CS Textbook for Edexcel' covers programming concepts including subprograms, data types, operators, and programming errors. It utilizes the PRIMM approach for teaching and includes Python examples with links to code files for practical application. The chapter emphasizes the importance of teaching programming concepts in a flexible order and provides various activities and exercises for students to engage with the material.

Uploaded by

smarinelli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.

net

6 – Programming
Specification Coverage

This chapter covers the following specification content from topic 1:


• 1.1.2 benefits of subprograms
• 1.2.2 variables, constants, strings, records and arrays
• 1.2.3 arithmetic, relational and logical operators
• 1.2.5 programming errors

This chapter covers all the specification content from topic 6 except the following
which are covered in chapter 1:
• 6.1.1 decomposition and abstraction
• 6.1.6 efficiency of algorithms

It is not necessary to teach this chapter in order. Use it as and when needed while
teaching students how to code. Centres are strongly advised to teach this
chapter before or alongside elements of chapter 1.

Python Files

Where Python has been used in examples, there will be two icons which are both
buttons that link to the original Python code. One icon is for the Python code in
Repl.it and the other is for the Python (.py) file:

Some activities will also include these buttons. Not all activities include the buttons
as running the Python code for those activities would make answering the question
too easy. There are several cases where there is a Python file framework for
answering tasks in an activity instead of an activity worksheet. Where answers are
provided using Python, many of the answer documents (both activity answers and
exam style question answers) will include links to Python files that include answers in
Python code, and often a step-by-step run through of the code. The icons used
for answers are:

These answer files can be used by the teacher to explain the answers to students
after they have completed the tasks, or by students once they have completed
the tasks. There are several cases where there is a Python file for answers to an
activity but not a separate Word document for the answers to an activity.
© paullong.net 2020 Page 1 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

PRIMM

This chapter follows the PRIMM approach to learning programming. Where


examples or activities use elements of PRIMM then it is denoted using the following
icons:

Predict what the program does


Run the program
Investigate how the program works
Modify the program
Make a new program

Flowcharts

Where flowcharts have been used there will be an icon which will open
the file created in draw.io

This free software can either be downloaded from http://tiny.cc/downloaddrawio


or used directly online from https://app.diagrams.net/

Visualising Variables
Use the trace variables visualisation tool at http://tiny.cc/tracevariables
to watch what happens to the value of the variables as each line is
executed. You can input any code into the tool. If inputs are required,
then add these, including if enter needs to be input.

© paullong.net 2020 Page 2 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Contents

1) Working with data ...................................................................................................... 5


Variable declaration (initialisation) ....................................................................... 5
Constant declaration ............................................................................................. 6
Assignment .............................................................................................................. 7
Output data to a computer display ..................................................................... 8
Obtain user input from the keyboard ................................................................... 9
2) Data types ................................................................................................................. 10
Character and string ............................................................................................ 10
Integer.................................................................................................................... 11
Real ........................................................................................................................ 12
Boolean.................................................................................................................. 13
Selecting data types ............................................................................................ 14
Casting ................................................................................................................... 14
3) Working with numbers .............................................................................................. 17
Basic arithmetic operators ................................................................................... 17
Integer division and remainder operators.......................................................... 18
Exponent operator ............................................................................................... 19
Mathematical functions ....................................................................................... 20
Built-in mathematical functions ................................................................ 20
Math module functions ............................................................................. 23
Random number functions .................................................................................. 25
4) String manipulation ................................................................................................... 28
Length .................................................................................................................... 28
Concatenation ..................................................................................................... 28
Slicing ..................................................................................................................... 29
ASCII ....................................................................................................................... 32
Formatting strings and numbers .......................................................................... 33
Field size ...................................................................................................... 33
Alignment.................................................................................................... 36
Formatting numbers ................................................................................... 38
Positional arguments.................................................................................. 41
Case conversion ................................................................................................... 42
Search functions ................................................................................................... 43
5) Programming concepts ........................................................................................... 49
Sequence .............................................................................................................. 49
Sleep ............................................................................................................ 49
Selection ................................................................................................................ 50
Multiple options .......................................................................................... 52
Nested selection ........................................................................................ 54
Iteration .................................................................................................................. 56
For loop ....................................................................................................... 56
While loop ................................................................................................... 62
Nested loops ............................................................................................... 64
6) Operators................................................................................................................... 70
Relational operators ............................................................................................. 70
Logical operators .................................................................................................. 72

© paullong.net 2020 Page 3 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

7) Data structures .......................................................................................................... 75


Arrays ..................................................................................................................... 75
Lists.......................................................................................................................... 80
Two-dimensional arrays ........................................... Error! Bookmark not defined.
Records .................................................................................................................. 87
Text files .................................................................................................................. 90
Read a text file ........................................................................................... 91
Write to a text file ....................................................................................... 98
8) Subroutines (procedures and functions) .............................................................. 104
Procedures .......................................................................................................... 105
Parameters .......................................................................................................... 107
Functions and return values ............................................................................... 107
Scope of variables .............................................................................................. 111
Decomposition and abstraction in programming .......................................... 113
Advantages of subroutines ................................................................................ 116
9) Turtle ......................................................................................................................... 119
Moving and turning ............................................................................................ 119
Setting positions .................................................................................................. 119
Turtle properties................................................................................................... 121
10) Maintainability of code .......................................................................................... 124
Meaningful identifier names .............................................................................. 124
Use unique words ..................................................................................... 124
Never use spaces ..................................................................................... 124
Use the underscore (_) to separate words . Error! Bookmark not defined.
Prefix the identifier .................................................................................... 125
Comments ........................................................................................................... 126
Use of constants .................................................................................................. 128
Indented code.................................................................................................... 129
White space ........................................................................................................ 130
Subroutines .......................................................................................................... 131
11) Robust and secure programming ......................................................................... 133
Validation routines .............................................................................................. 133
Presence check ....................................................................................... 134
Range check ............................................................................................ 135
Length check ........................................................................................... 136
Type check ............................................................................................... 137
Pattern check ........................................................................................... 138
Lookup check........................................................................................... 141
Accuracy .................................................................................................. 142
Authentication routines ...................................................................................... 143
12) Errors ......................................................................................................................... 147
Syntax errors ........................................................................................................ 147
Logic errors .......................................................................................................... 149
Runtime errors...................................................................................................... 151
Interpreting error messages ............................................................................... 152

© paullong.net 2020 Page 4 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

1) Working with data

Variable declaration (initialisation)

Variables contain data that can change throughout a program. A variable


reserves an area in memory to store its contents. In some programming
languages, any variables that are going to be used need to be declared. This
usually takes place at the beginning of a program for global variables or at the
beginning of a subroutine for local variables.

Global variables can be used throughout the whole programme, but local
variables can only be used within a subroutine.

In Python a variable is declared when it is first assigned a value, so it is not


necessary to declare a variable. However, it can be initialised with a value to set
its initial data type.

Example – variable initialisation


The following declarations are made in Visual Basic:

Dim i_counter As Integer


Dim s_forename, s_surname, s_title As String
Dim b_end_of_file As Boolean
Dim d_price As Decimal

The following variables are initialised using Python:

myText = ""
myInteger = 0
myFloat = 0.0
myBoolean = False
myArray = []

In Python a variable is declared when it is first assigned a value. The example


above initialises each variable by assigning it a blank or zero value.

A common analogy used for variables is to think


of it as a box. The box has a name, e.g. myText.

The name of the box (variable) does not change,


but its contents (data) can change.

The contents of this box (variable) have been


initialised to contain an empty string "".

© paullong.net 2020 Page 5 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Scratch Link – make a variable


The equivalent to variable declaration in Scratch is “make a variable”. For
example:

Constant declaration
Constants are values which cannot change while a program is running. There are
two types of constants: literal constants and named constants. Like variables,
constants also reserve an area in memory to store their contents.
Literal constants are when you use a constant value within the programming
code.

Example – literal constants


x = 0
print("Hello World")
result = x + 5

what will this program do?

run the program and see if your predictions were correct.

“Hello World” and 5 are both values that are used ‘literally’ within the
programming code.

Named constants need to be declared. These are usually values that mean
something and do not need to change.

Example – named constants


The following variables are initialised to be used as constants in Python:

DAYS_IN_YEAR = 365
PI = 3.142
GRAVITY = 9.8
MAX_COUNT = 100

Remember that in Python, variables do not need to be declared and so the


above initialisation is the process of setting up a variable to be used as a constant
by assigning it a value.

© paullong.net 2020 Page 6 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Assignment
The whole idea of having a variable is that it can change throughout
the program. When a value is assigned to a variable, the location of
that variable in memory stores the value. =
Scratch Link – set variables
This is an example of assigning the value 5 to the variable score:

This is an example of increasing the variable ballons_hit by 1

The Python symbol for assigning a value to a variable is =

Example – variable assignment


These are examples of vales being assigned to variables:
counter = 0 assigns the value 0 to the counter variable
lives = 3 assigns the value 5 to lives variable
score = lives * 3 assigns 3 times the number of lives to score
counter = counter + 1 adds 1 to the previous value of counter
class = "12N" assigns the value 12N to the class variable
end_ of_file = True assigns the Boolean value True to end_of_file

what will the value of score be?

run the program and see if your prediction was true.

These are examples of values being assigned to be used as if they were constants
by using the capital letters convention:

CLASS_SIZE = 28
PI = 3.14159

Activity – assignment
Write Python code to:
1) Assign the value 11 to the variable year_group.
2) Assign the Boolean value false to the variable game_over.
3) Assign the text value BLUE to the variable colour.
4) Increase the number_rooms variable by 4.
5) Assign the multiplication of variables class_size and number_rooms to
total_children.
6) Assign the value 7 to the constant days_in_week.
7) Assign the value 24 to the constant hours_in_day.
© paullong.net 2020 Page 7 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Maths Link – algebra


a = 5 is an example of assignment. 5 is assigned to the letter a. Other examples of
assignment in algebra include:

b = 20 c=a+b p = qr s = 5t

Output data to a computer display


To output data to a computer display, the Python code print can be used.

Example – output constant data to a computer display


To output “I am good at programming” to the computer display, you could use:

print("I am good at programming")

It is also possible to output data from variables to a computer display.

Example – output variable data to a computer display


To output the value of the variable surname, you could use:

surname = "Gates"
print(surname)

Variables and constants can be combined and displayed together by


concatenating (joining) them together.

Example – output concatenated data to a computer display


To output the name of a person and “is good at programming” to the computer
display, you could use this code:

surname = "Gates"
forename = "Bill"
print(forename + " " + surname + " is good at programming")

what will the output be?

If values are different data types, you could pass them as separate parameters:

print(forename, surname, "is good at programming")

run the program and see if your prediction was correct.

© paullong.net 2020 Page 8 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Obtain user input from the keyboard


Data can be obtained from the user by asking the user to input data using the
keyboard. The input function is used for this purpose in Python. The input from the
user must be assigned to a variable:
variable_name = input(<prompt to the user>)

Example – obtain user input from the keyboard


The code below asks the user for their name and then says hello to the user:

name = input("What is your name? ")


print("Hello", name)

You will find out more about how to specify datatype in the next section.

Activity – inputting and outputting data


The code below asks the user to enter two numbers. The numbers are then added
together and the result displayed on the screen.

number1 = int(input("Please enter the first number: "))


number2 = int(input("Please enter the second number: "))
total = number1 + number2
print("The total is", total)

what do you think will be displayed to the screen if the user inputs 20
followed by 50?

what do you think will happen if you do not use int()?

try inputting a letter – what happens and why did it happen?

Write code to ask the user for their forename, surname and the number of brothers
and sisters they have. Then display the full name and how many brothers and
sisters. For example, if Henry Wydale has 2 brothers and 0 sisters then the output
would be:

Henry Wydale has 2 brothers and 0 sisters.

Questions – follow me

1) Assign the value of the speed of light (299,792,458 m/s) to a constant integer
using Python. [1]

2) Describe the difference between a variable and a constant. [1]


© paullong.net 2020 Page 9 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

2) Data types

The computer needs to know how to handle data. Different types of data are
stored in different ways.

Character and string


A character can be a letter, symbol or number. You can find a list of characters
by looking at this ASCII table.

A string of data is a set of characters. It is often used to encompass the following


data types:

• Text Letters, symbols, characters and digits


• Alphanumeric Letters, digits or punctuation only

Python does not have a character data type. Instead, it just has strings as all single
character values can also be stored as a string.

Note: Edexcel will use the term character to mean the same as string in an exam.

Example – string data type


The following variables and values are examples of string data types:

Variable Data values Description


title Mr, Mrs, Prof Only letters are used.
forename Sarah, Gemma, Letters and a hyphen are used.
Jeanne-Marie
postcode B72 6PY Text, numbers and a space character are
used.
gender M, F Single characters are used.
telephone 020 842 950 A string of digits and spaces are used.
product_code 00351 This starts with a zero so it is a string of digits.
This is the Python code to receive the forename as input from the keyboard.

forename = input("Enter forename: ")

what do you think will happen if the user inputs "nine"?


what do you think will happen if the user inputs 9?
what do you think will happen if the user inputs “%$£t8"?

run the program and see if your predictions were correct.

© paullong.net 2020 Page 10 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Integer
This is a number data type. Integers are whole numbers. There are never any
decimal places or fractions in an integer.

Example – integer data type


The following variables and values are examples of integer data types:

Variable Data values Description


year 2012, 1945 A calendar year.
temperature -5, 0, 25 The temperature in Celsius.
distance 100, 200, Number of metres in a race.
400, 800
count 4, 8, 12 A counter used within a programming loop.

This is the Python code to receive the year as input from the keyboard.

year = int(input("Enter year: "))

The int() function converts the string input into an integer input.

what do you think will happen if the user inputs "twenty"?


what do you think will happen if the user inputs 20.0?
what do you think will happen if the user inputs 20?

run the program and see if your predictions were correct.

Notice how the distance above does NOT include “m” for metres. This is because
the character “m” is not part of an integer value and units should be displayed
separately.

A common misconception is that a telephone number is a number or integer data


type. This is not true. A telephone number is actually a string of digits. Each digit is
used to make a phone call. The telephone number is not actually a number. If it
was, then the phone number 0121 350 010 would actually be 121 million, 350
thousand and 10. It is in instead a set of digits, one after another, that can be used
to call a telephone. There are other reasons why a telephone number is a string
data type and not a number:

• it starts with a zero – a computer would not store the leading zeros if it was
represented as a numeric data type
• it includes spaces, or in some cases brackets or hyphens: (0121)-350-010
• it is not a number that will have calculations performed on it

© paullong.net 2020 Page 11 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – telephone numbers


Look at this code:

telephone = int(input("Enter telephone number: "))


print("telephone:", telephone)

what do you think will happen if the user inputs 0121 350 0010?
what do you think the output will be if the user inputs 01213500010?

run the program and see if your prediction was true.

What happened? Why do you think it happened?

Real
Real numbers include decimal places. Sometimes they are also sometimes called
float or double. In Python, they are called float.

Example – real data type


The following variables and values are examples of real data types:
Variable Data values Description
price 29.99, 0.85, Price of products in a shop.
120.00
track_time 9.85, 10.02 Number of seconds it took to run 100m.
distance 8.5, 9.12, 3.0 The distance between towns.

This is the Python code to receive the price as input from the keyboard.

price = float(input("Enter price: "))

The float() function converts the string input into a float input.

what do you think will happen if the user inputs 20?


what do you think will happen if the user inputs 20.0?
what do you think will happen if the user inputs "twenty"?
what do you think will happen if the user inputs "£20.00"?

run the program and see if your prediction was true.

As with the integer data type, units are not stored. Sometimes a price can be an
integer, although currency is most often stored as a real data type. For example,
the price of cars is often very high and so the prices will not include pence – in this
case the data can be stored as integers.
© paullong.net 2020 Page 12 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Boolean
Boolean data can only have one of two values. These values are “True” or “False”.
This can also be represented as “Yes” or “No”.

Example – Boolean data type


The following variables and values are examples of Boolean data types:
Variable Data values Description
passed_exam TRUE or FALSE Whether or not a person has passed an
exam.
end_of_file TRUE or FALSE Whether or not the end of a file has been
reached.
data_found TRUE or FALSE Whether or not a data item has been found.

This is the Python code to receive passed_exam as input from the keyboard.

passed_exam = bool(input("Did the student pass? "))

The bool() function converts the string input into a Boolean input. If any data is
input then the value will be True. If no data is input (e.g. "") then the value will be
False.

try inputting different values including just pressing enter


to leave the value blank. What happens if you input
"False"? Why do you think this is?

A common misconception is that Boolean data types include text fields where
data can be only two single character values, such as “M” or “F” for Male or
Female. However, this is not correct because they are not “Yes” or “No” / “True” or
“False” values. To be a Boolean data type, a person’s gender would have to be
stored as “Are you a male?” – with an answer of “Yes” or “No”. Just because a
field has two possible answers does not make it Boolean. The following examples
are not Boolean, they are string:

Field Data values Description


Gender M or F The gender of a person, M=Male, F=Female.
Transmission Manual or The type of gear box in a car.
Automatic
Level Junior or Senior The level of membership for a member.

© paullong.net 2020 Page 13 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Selecting data types


Here are some rules for choosing data types:

Field Data type


Does the data contain a single letter or symbol? CHAR
Does the data contain letters or symbols? STRING
Does the data contain only whole numbers? INTEGER
Does the data contain only numbers and a decimal point? REAL
Can the data only be “True” or “False”? BOOLEAN
Does the data start with a zero? STRING
Does the data include spaces? STRING

Activity – selecting data types


1) Identify the most appropriate data type for each of the following values:
a) 356 b) Garage c) p d) Yes e) True f) 5
g) 84.21 h) @ i) -273200 j) False k) £ l) 020 8888 7777

2) Identify the most appropriate data types for each of the following variables
used when collecting data about a house:
a) number_of_bedrooms b) has_a_garage
c) post_code d) price
e) estate_agent_name f) has_a_swimming_pool

Casting
Sometimes data starts life as one data type but needs to be converted to a
different data type for further manipulation. For example, if a number has been
extracted from a string and now needs to be used within a calculation, it will need
to be a real or integer to perform a calculation on it.

Casting is when programming code is used to deliberately (explicitly) change the


data type. Python includes the following casting functions:

String to Integer int(string_name)


String to Real float(string_name)
Integer to Real float(integer_name)
Integer to String str(integer_name)
String to Boolean bool(string_name)
Integer to Boolean bool(integer_name)
String to List list(string_name)

© paullong.net 2020 Page 14 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – casting
a = int("484") # evaluates to 484
b = float("359.20") # evaluates to 359.20
c = float(20) # evaluates to 20.0
d = str(90) # evaluates to "90"
e = bool(0) # 0 always evaluates to False
f = bool(1) # 1 always evaluates to True
g = bool("Any Text") # any string value always evaluates to True
h = bool("") # blank string always evaluates to False
i = list("hello") # evaluates to ["h", "e", "l", "l", "o"]

In Python, all data that is input from the keyboard is received as a string. Therefore,
if it needs to be used as a number, then it needs to be cast to an integer or a float.

Example – casting from input


score = int(input("What is the score? "))
weight = float(input("What is the weight in kg? "))

In Python, if you want to concatenate (join) variables together, then they need to
be the same data type.

Example – casting for concatenation


print("Your weight is " + str(weight) + "kg")
print("Your score is " + str(score) + " points")

Sometimes the data type is changed automatically (implicitly) by the program.


This is known as implicit coercion. In Python, this would happen if:

• an INTEGER is used in a calculation with a REAL to give an answer that is


REAL

Example – coercion
x = 3
y = 4
y = x + 5.5
x += 2.4

what will the value of x be?


what will the value of y be?

run the code and see if your predictions were correct.

Although y started life as an integer, it is now automatically changed to a real


because a real value was used in the calculation. x also becomes a real when 2.4
is added to it.
© paullong.net 2020 Page 15 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – casting

1) Predict the value of <answer> in each of the following sets of code:


a) answer = str(3)
b) answer = float("245.03")
c) answer = float("10.420")
d) answer = bool("False")
e) answer = list("False")
f) answer = list("230.8")

2) Look at the code below:

score = input("What is the score?")


score = score * 10

a) What do you think the value of score would be if the code


above was run and the input was 3?

b) Why do you think this has happened?

c) Modify the code so that it multiplies the score by 10 correctly.

3) Write code to convert the following:


a) “51” from string to integer
b) 78.2 from real to string
c) “12.90” from string to real
d) the cost of a book input by a user to real.

Questions – follow me
1) Describe the difference between a character data type and a string data
type. [2]

2) Describe the difference between an integer and a real data type. [2]

3) Explain why telephone number is not an integer data type [2]

4) List two possible values for a Boolean data type. [2]

5) A user is asked to input the cost of a holiday. Using an example related to the
cost of the holiday, explain why casting might be necessary in Python. [3]

© paullong.net 2020 Page 16 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

3) Working with numbers

Basic arithmetic operators


Basic arithmetic operators are the use of:

• addition
• subtraction
• multiplication
• division

Programming languages do not usually recognise x for multiply or ÷ for divide. In


Python, the following symbols are used:

+ add - subtract * multiply / divide

Values can be calculated and assigned to a variable. Calculations can also


include a variable.

Example – basic arithmetic


price1 = 5 + 6 adds 5 to 6 and assigns result of 11 to price1
price2 = 8 * 9 multiplies 8 by 9 and assigns 72 to price2
new_value = 20 / 4 divides 20 by 4 and assigns 5 to new_value
price1 = price1 – 6 subtracts 6 from the current value of price1 and
assigns new value to price1
total = price1 + price2 adds contents of price1 to contents of price2
and assigns to total

my_number = (total + new_value) * price1 / price2


adds contents of new_value to contents of total, then multiplies the result by
price1 and divides by price2 and then assigns to my_number

Maths link – BIDMAS


BIDMAS is an acronym used in maths to help remember the correct order in which
to solve maths problems:

Brackets
Indices
Division
Multiplication
Addition
Subtraction
© paullong.net 2020 Page 17 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Calculations within brackets should always be calculated first. After that, any
indices (exponent) calculations should take place, followed by
division/multiplication, then addition/subtraction – in that order.

It is important to get this right in programming. If in doubt, use more brackets.

Check your understanding with the BBC Bitesize test at http://tiny.cc/bidmas

Activity – basic arithmetic


Write code for the following algorithms, displaying each answer on the screen:
1) Ask the user for a number and multiply it by 5.
2) Add together 2 numbers entered by the user.
3) Ask the user for 2 numbers. Divide the first number by the second number.
4) Ask the user for 4 numbers – a, b, c and d. Multiply a by c, then add d and
divide everything by b.

Integer division and remainder operators


When using / for divide the computer will give the result as a real number which
could include decimal places. There are occasions when you just want to know
the whole number part of the answer or the remainder part of the answer.

Integer division uses // and will give the result as the whole number part of a
division.

Example – integer division


total = 6 // 3 6÷3=2 so 6 // 2 = 2
total = 16 // 5 16 ÷ 5 = 3.2 so 6 // 5 = 3
d = 85 // 10 85 ÷ 10 = 8.5 so 85 // 10 = 8
y = 114 // 5 114 ÷ 5 = 22.8 so 114 // 5 = 22

To calculate the remainder, % can be used to give the remainder part. This is
known as the modulus.

Example – remainder
total = 6 % 3 6÷3=2r0 so 6 % 2 = 0
total = 16 % 5 16 ÷ 5 = 3 r 1 so 6 % 5 = 1
d = 85 % 10 85 ÷ 10 = 8 r 5 so 85 % 10 = 5
y = 114 % 5 114 ÷ 5 = 22 r 4 so 114 % 5 = 4
z = z % 8 the remainder will be between 0 and 8.

© paullong.net 2020 Page 18 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Scratch Link – remainder


This Scratch example finds the remainder of a
number chosen by the user divided by 5.

Maths Link – remainders


Revise how to calculate remainders in maths at http://tiny.cc/remainders from BBC
Bitesize.

Activity – integer division


1) Predict the value of answer in each of the following:
a) answer = 80 // 11
b) answer = 80 % 11

2) Write code to calculate the following and assign to the variable <answer>:
a) The whole number part of the integer division of 200 ÷ 9.
b) The whole number part of the integer division of 372 ÷ 7.
c) The whole number part of a number chosen by the user ÷ 7.
d) The whole number part of a number chosen by the user divided by
another number chosen by the user.

3) Write code to calculate the following and assign to the variable <answer>:
a) The remainder when 393 is divided by 16.
b) The remainder when 901 is divided by 19.
c) The remainder when 1000 is divided by a number chosen by the user.
d) The remainder when a number chosen by the user is divided by another
number chosen by the user.

Exponent operator
The exponent is often referred to as the index or power.

Maths Link – exponent


a2 = a x a a3 = a x a x a a4 = a x a x a x a

The exponent is 2, 3 and 4 in the above examples. If a is 5, then:

52 = 5 x 5 = 25 53 = 5 x 5 x 5 = 125 54 = 5 x 5 x 5 x 5 = 625

© paullong.net 2020 Page 19 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

In Python, the ** symbol is used to calculate the exponent.

Example – exponent
total = 2**3 23 = 2 x 2 x 2 so total = 8
total = 4**2 42 = 4 x 4 so total = 16
x = 5**4 54 = 5 x 5 x 5 x 5 so x = 625

Activity – exponent
1) Predict the value of answer in each of the following:
a) answer = 5 ** 2
b) answer = 2 ** 7

2) Write code to calculate the following and assign to the variable <answer>:
a) 6 to the power of 2.
b) 4 to the power of 3.
c) 2 to the power of 4.
d) 5 to the power of a number chosen by the user.
e) A number chosen by the user to the power of another number chosen by
the user.

3) Write code to calculate the following:


a) The area of a square. The user should be asked for the length of the sides.
b) The volume of a cube. The user should be asked for the length of the
sides.

Mathematical functions

Built-in mathematical functions


The round function can be used to round a float (real) number to a set number of
decimal places. Its structure is:
round(number, dp)

This will round a number to the number of decimal places indicated by dp.

Example – round
answer = round(25.876, 2) 25.876 to 2dp so answer = 25.88

answer = round(18.0004, 3) 18.0004 to 3dp so answer = 18.0

answer = round(9.2764, 1) 9.2764 to 1dp so answer = 9.3

© paullong.net 2020 Page 20 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

answer = round(9.2, 0) 9.2 to 0 dp so answer = 9.0

what the following code will give as an answer.


answer = round(9.2)

the difference between using round(9.2, 0) and round(9.2).

Activity – round
1) Predict the value of answer in each of the following:
a) answer = round(30.253, 2)
b) answer = round(138.253892, 4)

2) Write code to calculate the following and assign to the variable <answer>:
a) 27.1028 rounded to 3 decimal places
b) 18.00042 rounded to 4 decimal places
c) 120.2 rounded to 0 decimal places.

3) Did you notice that the value of the answer for 2(c) actually displayed as one
decimal place even though you had asked it to round to zero decimal
places?
a) Explain why has this happened?
b) Modify the code from 2(c) so that it does not display any decimal places.

Extension:
4) Predict the value of answer in each of the following:
a) answer = round(4.5)
b) answer = round(7.5)
c) answer = round(8.5,0)
d) answer = round(11.5,0)
e) answer = round(4.15,1)
f) answer = round(4.25,1)
g) answer = round(4.35,1)

5) a) Run the code. What unexpected results did you find?


b) Is there a pattern? Experiment with other values if you
need to try some more.

© paullong.net 2020 Page 21 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

The range function can be used to produce a list of numbers within a range:
range(start, stop, step)

This will produce a list of numbers in a range starting at value start and ending at
the value before stop. For example, if stop is 10, then the ending value will be 9.

If a number is entered for step, then this will be the gap between each number in
the range. If a number is not entered for step, then the gap will be one (1) by
default.

Example – range
In these examples, the list function has been used to generate a list from the range
of values. You will learn more about the list function in the using lists section.

answer = range(1, 5)
print(list(answer)) this will produce [1, 2, 3, 4]

Notice how the range of values stops at 4, which is one below the stop value of 5.
The stop value in the range function is not inclusive, but the start value is.

answer = range(12, 18)


print(list(answer)) this will produce [12, 13, 14, 15, 16, 17]

In the example above, the gap between each number has not been specified
and so it is set to the default of 1. In the example below you can see how
including the step of 1 gives the same result as above.

answer = range(12, 18, 1)


print(list(answer)) this will also produce [12, 13, 14, 15, 16, 17]

The next examples use larger step values.

answer = range(1, 8, 2) this sets a gap of 2 between each number


print(list(answer)) this will produce [1, 3, 5, 7]

answer = range(0, 51, 10) this sets a gap of 10 between each number
print(list(answer)) this will produce [0, 10, 20, 30, 40, 50]

Activity – range
1) Predict the value of answer in each of the following:
a) answer = range(0, 10)
b) answer = range(1, 15, 2)
c) answer = range(100, 190, 10)

© paullong.net 2020 Page 22 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

2) Write code to produce a range of values for each of the


following and assign to the variable <answer>:
a) 5, 6, 7, 8, 9, 10
b) 2, 4, 6, 8, 10
c) 50, 55, 60, 65, 70, 75
d) The values on a six-sided dice.

Math module functions


The operators and functions you have used so far have been built-in to Python.
There are other mathematical functions available and some of these are in a
separate module called math. To access these functions, you need to import the
math module into your Python code:

import math

It is good practice to import modules all together at the start of a program.

The math functions that you need to be able to use for Edexcel are:
math.pi gives the value of Pi to 15 decimal places
math.sqrt(number) calculates the square root of a number
math.floor(number) returns the largest integer value less than a number
(similar to rounding down to zero decimal places
for positive numbers)
math.ceil(number) returns the lowest integer value higher than a
number (similar to rounding up to zero decimal
places for positive numbers)

Example – math module functions


The code below gives the value of Pi to 15 decimal places:

pi = math.pi = 3.141592653589793

The code below calculates the square root of 81:

answer = math.sqrt(81) = 9.0

The code below finds the largest integer value less than 25.67:

answer = math.floor(25.67) = 25

The code below finds the lowest integer value higher than 25.67:

answer = math.ceil(25.67) = 26

© paullong.net 2020 Page 23 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – math module functions


1) Predict the value of answer in each of the following:
a) answer = round(math.pi, 3)
b) answer = math.sqrt(25)
c) answer = math.ceil(12.01)
d) answer = math.floor(5.99)
e) answer = math.ceil(-5.6)
f) answer = math.floor(-5.6)

2) Run the code above. Were your predictions correct? What was unexpected
or noticeable about the answers to 1f and 1g?

3) a) Modify the code for 1d so that it casts the float value 5.99 to an integer.
You may find the int function helpful.
b) Does this give the same result as 1d?
c) Modify the code for 1f so that it casts the float value -5.6 to an integer.
d) Why does this give a different result to 1f?

4) Write code to calculate the following and assign to the variable <answer>:
a) The square root of -49
b) The value of Pi to 2 decimal places
c) The floor value of 119.52
d) The ceiling value of 2.08
e) Casting the float value of -6.8 to an integer
f) Rounding the float value of -6.8 to 0 decimal places
g) The floor value of -6.8.

You have probably noticed by now that for positive float (real) numbers, the int
function does exactly the same as the math.floor function. However, it works
slightly differently. The int function truncates the decimal values. The math.floor
function rounds down to the nearest whole integer.

The difference is noticeable when using negative numbers.

© paullong.net 2020 Page 24 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Extension example – int vs floor


Run the examples of code below and investigate the different
answers that are given. Experiment with different values.

answer = int(-5.6) truncates the decimal answer = -5

answer = math.floor(-5.6) rounds down to nearest integer answer = -6

answer = round(-5.6, 0) rounds to 0 decimal places answer = -6.0

answer = round (-5.6) rounds to the nearest integer answer = -6

answer = round (-5.2) rounds to the nearest integer answer = -5

answer = int(-5.6) truncates to an integer answer = -5

Random number functions


A random number is one which is generated without any
method or conscious decision. It is unpredictable what
number could be chosen, although statistically a good
guess could be made. In programming, it is a bit more
complicated because a genuinely random number is
not possible. However, it is possible to generate a
number that is nearly random (i.e. it appears to be random), known as pseudo-
random. Random numbers are very useful in games and quizzes.

Maths Link – dice


If you throw a dice, you will get a random value between 1 and 6. Keep
repeating this and you will have a set of values between 1 and 6.

Imagine you through the dice 10 times. It is possible, although not probable, that
this could happen:

You could also throw 10 ones or 10 twos, but it is more likely there will be a mixture
of numbers.

The probability of throwing any single number is one in six or 1/6 because there are
six numbers in total.

© paullong.net 2020 Page 25 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

To use random functions you will need to import the random module in Python:
import random

To generate a random floating point number (real) between 0.0 and 1.0, use the
following code:

random.random()

Example – random numbers


To find a random number between 0.0 and 1.0, use:
import random
answer = random.random()

To generate a random integer, use the following code:


random.randint(start, end)

The start variable represents the lowest integer the random number can be. The
lowest integer is zero (0). The end variable represents the highest integer the
random number can be. You will need to import the random

Example – random integers


To roll an imaginary dice and find a random number between 1 and 6, use:
dice = random.randint(1,6)

To find a random number between 0 and 999,999, use:


answer = random.randint(0,999999)

To find a random multiple of 100 between 0 and 1,000,000, use:


answer = random.randint(1,10000) * 100

Activity – random numbers


Write code to generate each of the following:
1) A random integer between 1001 and 9999.
2) A multiple of 5 between 5 and 100.
3) To throw an imaginary coin returning either heads or tails. Hint: use 2
numbers to represent heads and tails.
Extension: A random uppercase letter. Hint: use char.

Video
Extension: Watch http://tiny.cc/randomnumbers about how computers can use
the time to generate random numbers from YouTube.

© paullong.net 2020 Page 26 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Questions – follow me

1) Which arithmetic operator should be used in place of ❑ in each line of code


below to give the result shown? [5]
a) 5 ❑ 6 = 11
b) 29 ❑ 10 = 2
c) 300 ❑ 6 = 50
d) 40 ❑ 3 = 120
e) 413 ❑ 40 = 13
f) 6 ❑ 2 = 36

2) Describe the difference between the // and % operators. [2]

3) Write code to calculate how many slices of pizza each person will get and how
many slices will be left over. The program should ask the user for the number of
people, the number of pizzas and the number of slices per pizza. [4]

4) Write code to calculate the area of a circle rounded to 2 decimal places


when the user inputs the radius. [3]

5) List all the possible values of <answer> in the code below: [3]
a) answer = random.randint(0, 5)
b) answer = random.randint(0, 10) * 10

6) Write code to ask the user how many sides they want on their dice (e.g. 12).
Roll an imaginary dice and return a value randomly. [2]

© paullong.net 2020 Page 27 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

4) String manipulation

A string is a set of characters. “Programming” is the set of characters “P”, “r”, “o”,
“g”, “r”, “a”, “m”, “m”, “i”, “n”, “g”.

Note: Edexcel use the data type char to mean string.

Example – string characteristics


The word “Programming” has 11 characters.
The 4th character is “g”, assuming counting starts at 1.
The word “gram” is found from character 4 to character 7.

Length

The length of a string is the number of characters within the string. This can be
calculated in Python using LEN:

len(stringName)

Example – length of a string


surname = "MacDonald"
phoneNumber = "0777555555"
length = len(surname)
length2 = len(phoneNumber)

The value of <length> will be 9 because there are 9 characters in MacDonald.


The value of <length2> will be 10 because there are 10 characters in 0777555555.

Concatenation
Concatenation is the process of joining. To concatenate two strings is to join two
strings. The + symbol is used to concatenate two or more strings.

string_1 + string_2 + string_3

Example – concatenation
surname = "MacDonald"
forename = "Ronald"
fullname = forename + " " + surname

The value of <fullname> is “Ronald MacDonald”. The value of <fullname> is


calculated by starting with the value of <forename>, appending a space and
then appending the value of <surname>.

© paullong.net 2020 Page 28 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Predict what you think the value of answer will be in the following
when the values of 20 and 40 are input:

value1 = input("Please enter value 1: ")


value2 = input("Please enter value 2: ")
answer = value1 + value2

Did you predict 60? Run the code and see what the result is. Why do you think the
answer was different to 60?

Slicing
Slicing is the process of extracting part (a slice) of a string. For example, “gram” is
a slice of “Programming”.

It is possible to extract a character in a specific position (index) within a string. It is


important to remember that the first position (index) is always zero (0):

Index (position) 0 1 2 3 4 5 6
Value P r o g r a m

To extract a character use:

character = string[position]

Example – position in a string


surname = "MacDonald"
initial = surname[0]

The value of <initial> will be “M” because M is the first character which is
position 0 (indexing starts at 0 in Python).

what do you think the value of letter will be in the code below?

letter = "Computer"[4]

the code. Were you right?

Remember that indexing starts at 0.

© paullong.net 2020 Page 29 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

The example above returns a single character within a string. Slicing can also
return several characters from a string:

answer = string[start:end] returns a slice of a string starting at


index start and ending at the
character before index end

answer = string[:end] returns a slice of a string starting at the


beginning of the string and ending at
the character before index end

answer = string[start:] returns a slice of a string starting at


index start and ending at the last
character of the string

Like with the range function, the end index is not inclusive of the value at that
position. To count from the end of the string instead of the start of the string,
negative numbers can be used.

Example – slicing
what the value of answer will be in each line of code below.

surname = "MacDonald"
answer = surname[0:3]
answer = surname[3:6]
answer = surname[3:]

myString = "Comprehension."
answer = myString[8:]
answer = myString[:4]
answer = myString[-1:]
answer = myString[-4:]
answer = myString[:-1]
answer = myString[:-6]
answer = myString[-6:-4]

the code. Were you correct?

using different index (position) values.

© paullong.net 2020 Page 30 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – string manipulation

1) Predict the value of <answer> in each of the following sets of code:


a) answer = len("Mississippi")
b) answer = len("Count every character!")
c) answer = len("(0908)-283929")
d) answer = "Mississippi"[0]
e) answer = "Count every character!"[7]
f) answer = "Mississippi"[0:4]
g) answer = "Count every character!"[6:12]
h) value1 = "Emma"
value2 = "Willis"
answer = value2 + ", " + value1 + "."

were your predictions correct?

2) Write code to find the following:


a) length of the phrase “Wish you were here”.
b) length of a word or phrase input by the user.
c) the last character of “Please help me”.
d) the last character of a word or phrase input by the user.
e) the last 4 characters of “I like chocolate”.
f) the first 3 characters of a word or phrase input by the user.
g) the last 5 characters of a word or phrase input by the user.

© paullong.net 2020 Page 31 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

ASCII
Note: You may find it useful to read chapter 2 section 4 about data representation
using ASCII before this part.

It is possible to convert characters to their ASCII code (or Unicode) or to convert


an ASCII code (or Unicode) to a character. This can be particularly useful when
using control codes such as LF (line feed) or CR (carriage return).

To convert a character to its character code, use the following code:

ord(character)

To convert a character code to its character, use the following code:

chr(code)

The value of the character variable should be any single character and the value
of the code variable should be any integer value in the range used for Unicode.

Example – character codes


The following code returns the value 68:
answer = ord("d")

The following code returns the value “>”:


answer = chr(62)

To create a character code for Ɏ, use the following code:


answer = chr(590)

Activity – character codes

1) Using an ASCII table, predict the value of answer in each of the following
lines of code:
a) answer = chr(52)
b) answer = chr(163)
c) answer = chr(9) + "."
d) answer = ord("q")

2) Write code that uses character code conversion to produce the following:
a) the ASCII / Unicode value of T
b) the character {

© paullong.net 2020 Page 32 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Formatting strings and numbers


The format that strings and numbers are displayed as can be changed using the
format method. The format method defines how data should be displayed:

str.format() where str is a string

Field size
The amount of space that data uses up on screen is determined by its width (or
field size). For example, the word “Programming” would use up 11 characters so
has a width (or field size) of 11. We are going to look at why this makes it difficult to
put data into a tabular format.

Example – data in a tabular format


We are going to use a set of data about students which includes their forename,
surname and tutor group. The data is stored in a list and we are going to use a for
loop to work through the list. Lists and loops are programming concepts we will
cover later, so you just need to focus on the part that displays data on the screen.

This code defines 4 students:

students = [["Chelsea", "Bartholomew", "10B"],


["Amy", "Argue", "10C"],
["Ann-Marie", "Ferguson-Andrews", "10C"],
["Kapil", "Jatily", "10B"] ]

This code will work through each student but the important part you need is the bit
that displays the data on the screen:

for student in students:


forename = student[0]
surname = student[1]
tutorGroup = student[2]
print(forename, surname, tutorGroup)
#next student

the code and you will find the output of this data looks like this:

Chelsea Bartholomew 10B


Amy Argue 10C
Ann-Marie Ferguson-Andrews 10C
Kapil Jatily 10B

© paullong.net 2020 Page 33 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

This is very difficult to read and ideally we would like it to look like this:

Chelsea Bartholomew 10B


Amy Argue 10C
Ann-Marie Ferguson-Andrews 10C
Kapil Jatily 10B

We could try using the code for a tab character:

print(forename, "\t", surname, "\t", tutorGroup)

When you run this code, all it does is to move the text to the next tab position. With
some long and short names, this does not help, as the data is still difficult to read:

Chelsea Bartholomew 10B


Amy Argue 10C
Ann-Marie Ferguson-Andrews 10C
Kapil Jatily 10B

Instead, we can use the format method to specify a fixed width for each item of
data. In this example, we will fix the width as follows:

forename 15 characters
surname 20 characters
tutorGroup 3 characters

This is the code we will use:

print("{:15}{:20}{:3}".format(forename, surname, tutorGroup))

When you run the code you can see the output looks like what we were hoping
for:

Chelsea Bartholomew 10B


Amy Argue 10C
Ann-Marie Ferguson-Andrews 10C
Kapil Jatily 10B

© paullong.net 2020 Page 34 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

The output is set out in columns. The table below shows how columns 1-15 (width
of 15) are used for the forename, 16-35 (width of 20) are used for the surname and
36-38 (width of 3) are used for the tutor group.
1 5 10 15 1 5 10 15 20 1 2 3
Columns 1-15 (forename) Columns 16-35 (surname) 36-38
C h e l s e a B a r t h o l o m e w 1 0 B
A m y A r g u e 1 0 C
A n n - M a r i e F e r g u s o n - A n d r e w s 1 0 C
K a p i l J a t i l Y 1 0 B

Activity – data in a tabular format


1) Try changing the code so that different widths are used.

2) What is the smallest width you can use for forename and surname before
the output is not displaying properly?

3) Try changing the order in which each item of data about the student is
displayed on each row.

Example – field size


The example above shows why we would use the format method to set the width.
Run the examples below to investigate how the field size can be used on a single
string.

print("{:15}".format("Hello World"))
print("{:25}".format("Hello World"))
print("{:5}".format("Hello World"))

Did you notice that none of these made any difference to a single string? That is
because we cannot see the space that is being used.

The code has now been adapted to include some additional text “---field ends
here” to show the effect the field width has:

print("{:15}---field ends here".format("Hello World"))


print("{:25}---field ends here".format("Hello World"))
print("{:5}---field ends here".format("Hello World"))

Did you notice that even though a field size of 5 was used, the whole of “Hello
World” was displayed? This is because the field size is a minimum width rather than
a fixed width.
© paullong.net 2020 Page 35 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Alignment
The field size becomes a lot more useful when aligning data. We can align data to
the left, centre or right within a width (field size). The following codes can be used
for alignment:

< left align


> right align
^ centre align

Example – alignment
Run the code below to investigate how the word “Hello” can be aligned within a
field size of 50:

print("{:<50}".format("Hello"))
print("{:>50}".format("Hello"))
print("{:^50}".format("Hello"))

The example above uses “Hello” as a literal constant but a variable containing a
string could also be used:

myString = input("\nPlease input a word to be aligned: ")


print("{:<50}".format(myString))
print("{:>50}".format(myString))
print("{:^50}".format(myString))

Investigate how this code aligns strings by inputting different string values, e.g. “This
is my string”.

the code to use different field sizes

The example above will align the data within the field size, but it is difficult to see
the unused space. We can fill the unused space with characters. This is known as
padding. To fill the unused space, simply enter the character that should be used
before the alignment symbol.

Example – padding
Run the code below to investigate how the hyphen has been used as padding:

print("{:-<50}".format("Hello"))
print("{:->50}".format("Hello"))
print("{:-^50}".format("Hello"))

© paullong.net 2020 Page 36 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Continue to run the next part of the code to see how an asterisk (*) has been used
instead of a hyphen:

myString = input("\nPlease input a word to be aligned: ")


print("{:*<50}".format(myString))

the code to use different characters for padding, different field sizes
and different alignments. See if you can create

Activity – alignment and padding


1) Write code using the format method with centre alignment to create the
hourglass shape below:

xxxxxxxxxx
xxxxxxxx
xxxxxx
xxxx
xx
xxxx
xxxxxx
xxxxxxxx
xxxxxxxxxx

2) Write code using the format method with alignment and padding to create
the rhombus shape below:

oooooooooooooooooooooooo ooooooooooooooooooooooooo
ooooooooooooooooooooooo oooooooooooooooooooooooo
oooooooooooooooooooooo ooooooooooooooooooooooo
ooooooooooooooooooooo oooooooooooooooooooooo
ooooooooooooooooooooo oooooooooooooooooooooo
oooooooooooooooooooooo ooooooooooooooooooooooo
ooooooooooooooooooooooo oooooooooooooooooooooooo
oooooooooooooooooooooooo ooooooooooooooooooooooooo

3) Experiment using the format method with different alignments, field widths
and padding to create different shapes.

© paullong.net 2020 Page 37 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Formatting numbers

You saw in the data types section how to cast an integer to a real and a real to an
integer, and you have also seen how to use integer division, round, floor and ceil
functions. All of these will change the data. However, there are times when you
just need to be able to format a number so that it looks right. The format method
can be used to format float (real) numbers to a specific number of decimal places
or to align numbers.

The following codes can be used for numbers:

f fixed number of decimal places (fixed point)


d align integers

Example – decimal places


Run the code below to investigate how the number of decimal places (fixed
point) has been set:

print("{:.0f}".format(3.14159259))
print("{:.2f}".format(3.14159259))
print("{:.10f}".format(3.14159259))

Did you notice that if more decimal places are specified than exist, then there are
trailing zeros?

Run the code below to see how the number of decimal places (fixed point) can
also be used within a field size (width). This enables numbers to be aligned on the
decimal point:

print("{:8.4f}".format(3.14159259))
print("{:8.4f}".format(485.67921928))
print("{:8.4f}".format(28.6))

This can be particularly useful when dealing with currency. Run the code below
and notice how the £ sign has been included in the output before the formatting
of the numbers:

print("£{:8.2f}".format(19.62))
print("£{:8.2f}".format(284.91))
print("£{:8.2f}".format(1.2))

© paullong.net 2020 Page 38 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – decimal places

1) What do you think will happen if you run the code below?
a) How will the numbers be formatted?
b) Will all the numbers be displayed?
c) How will they be aligned?

print("{:8.2f}".format(284.913))
print("{:8.2f}".format(1.2))
print("{:8.2f}".format(102956748.6))

2) Run the code and see if your prediction was correct. Discuss with others in
your class why you think this has happened.

3) Write code for the following:


a) format 251.82062 to 2 decimal places
b) format 29.6 to 4 decimal places
c) format 12.52 to 1 decimal place with a field size of 7
d) format 8100 to 2 decimal places in dollars

4) Modify the code below to display the numbers in a column aligned by the
decimal point:

print(104.23)
print(92.2467)
print(8.001)
print(5291)

The d option can be used to align integers to the right within a field size (width)
and to also cast the integer to a string.

© paullong.net 2020 Page 39 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – formatting integers


what the output of this code will be:

x = 10
y = "{:d}".format(x)
print(y*2)

the code. Was your prediction correct? What do you think has
happened?

The d setting means that the integer is cast to a string. Therefore, two lots of 10
(one zero) are 1010 (one zero one zero).

The d setting also aligns the data to the right within a field size (width). Run the
code below and then modify it to use different widths.

Run the code below to investigate how the number of decimal places (fixed
point) has been set:

print("{:5d}".format(x))
print("{:5d}".format(10 * x))
print("{:5d}".format(100 * x))
print("{:5d}".format(1000 * x))

Predict what the code below will do. Run the code to investigate what it does.
Modify the code to see what happens when you use different numbers and
decimals.

print("{:,}".format(10000000))

Activity – formatting integers

1) Write code for the following:


a) cast 3000 to a string using the format method
b) display these 4 numbers as integers aligned to the right:
20 32018 3 4927

© paullong.net 2020 Page 40 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

2) Modify the code below to display the numbers input by the user to the right:

num1 = input("Please input first number: ")


num2 = input("Please input second number: ")
num3 = input("Please input third number: ")
print(num1)
print(num2)
print(num3)

3) Try inputting long numbers. Discuss what limitations there might be to your
modified code from question 2.

Positional arguments
One method of including multiple items of data in a single print statement is to
send them as multiple arguments (parameters). Another method is to use the
format method with positional arguments (parameters).

Note: Edexcel refer to these as “positional arguments”. The correct term is


“positional parameters” but it is beyond GCSE level to understand the
difference between parameters and arguments.

Example – positional arguments


The following variables have been assigned values:

firstname = "Paul"
score = 5
teacher = "Mrs Robinson"

We want to display on the screen:

Hi Paul, you scored 5 points. Well done Paul, your teacher


Mrs Robinson will be notified

One way of doing this would be to use multiple arguments within a print statement:

print("Hi", firstname, ", you scored", score,


"points. Well done", firstname, "your teacher",
teacher, "will be notified")

© paullong.net 2020 Page 41 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Run the code above and investigate how it works.

Another way of doing this is to use positional arguments using the format method:

print("Hi {0}, you scored {1}


points. Well done {0}, your teacher
{2} will be notified".format(firstname, score, teacher))

The arguments (references to variables) of firstname, score and teacher are


passed to the format method. These can then be referenced as {0}, {1} and
{2}. They can also be re-used as you can see firstname has been used twice

The Edexcel Programming Language Subset (PLS) guide includes this example:

print("{:>10} string,{:^5d} integer,{:7.4f} a real"


.format("Fred", 358, 3.14159))

Notice how each value has only been used once and so it is not necessary to
reference them as 0, 1, 2. Also notice how each positional argument has been
formatted.

Run the code and investigate what it does.

Experiment by modifying the three sets of code above to see what happens when
you make changes to the values, formats and order of variables.

Case conversion
It is possible to change the case of data using the upper and lower methods.

Example – case conversion


To change the case of “hello” to be “HELLO” use the following code:

myString = "hello".upper()
print(myString)

© paullong.net 2020 Page 42 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Changing the case can be useful when comparing user inputs. The code below is
designed to decide if a user would like to quit a program:

quit = input("Would you like to quit? y/n: ")


if quit == "y":
print("You chose to quit")
else:
print("You chose not to quit")
#endif

what would happen if the user input the following responses:


Y N y n

Run the code. Was your prediction correct?

Activity – case conversion


Using the lower method, modify the code from the example
above so that it will work as intended whether the user inputs
lower-case or upper-case responses.

Search functions
There will be occasions when you need to find a substring within a string or replace
a substring with another string. The functions below allow you to search for a
substring within another string:

Function Purpose Example


find Find a substring within a string and "Hello".find("e")
return its starting position (index) or Result is 1
-1 if not found.
index Find a substring within a string and "Hello".index("o")
return its starting position (index) or Result is 4
raise an exception if not found.
replace Find a substring within a string and "Hello".replace("lo", "p")
replace it with a different value. Result is "Help"
strip Finds characters at the beginning "...Hello,,,".strip(",.")
and end of a string and removes Result is "Hello"
them.
split Finds a character within a string "One,Two,Three".split(",")
and splits the string into a list of Result is:
values separated by that ['One', 'Two', 'Three']
character.

© paullong.net 2020 Page 43 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – find
The code below will search the word “Hello” for the value “e”. If “e” exists, it will
return its position (1):

answer = "Hello".find("e")

the value of answer1 and answer2 in the code below:

myWord = "Programming"
answer1 = myWord.find("gram")
answer2 = myWord.find("me")

the code above and see if your predictions were correct.

the code above to use different strings and substrings.

Activity – find
Write code to:

1) Ask the user for a letter to search for in the word


“Programming”.

2) Ask the user for a word or phrase that they would like to search. Then search
for “the” within that word or phrase.

3) Ask the user for a word or phrase that they would like to search. Ask the user
for a substring that they would like to find. Then search for the substring
within the word or phrase.

The index function can be used in a similar way to find, but if the substring is not
found within the string, then an exception (error) is raised instead of -1.

Activity – index
Open the code used in the example for the find function:

myWord = "Programming"
answer1 = myWord.find("gram")
answer2 = myWord.find("me")

the code so that index is used instead of find for each example.

what you think value of answer1 and answer2 will be.

© paullong.net 2020 Page 44 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Experiment with the code below using different values for myWord and
mySubString:

myWord = input("Input a word or phrase that you would like to


search: ")
mySubString = input("Input a substring that you would like to
search for in " + myWord + ": ")
answerFind = myWord.find(mySubString)
answerIndex = myWord.index(mySubString)

Which function (index or find) will be the more robust to use when the string to
be searched and/or substring to be found are unknown? Justify your answer using
the code above as an example.

The replace function can be used in a similar way to find, but if the substring is
found, then it is replaced with another substring.

Example – replace
The code below will search the word “Hello” for the substring “lo”. If “lo” exists, it
will replace it with “p” and return “Help”:

answer = "Hello".replace("lo", "p")

Activity – replace
Open the code used in the example for the find function:

the value of x , y and z in the code below:

txt = "I like bananas"


x = txt.replace("bananas", "apples")
y = txt.replace("apples", "oranges")

spacedOut = " Hello ."


z = spacedOut.replace(" ", "")

the code to experiment with different values.

The strip function can be used to remove characters from the beginning and
end of a string. It will strip each character individually.

© paullong.net 2020 Page 45 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – strip
The code below will search for the characters “,” and “.” in the string
"...Hello,,," and remove them from the beginning and end of the string.

answer = "...Hello,,,".strip(",.")

The value of answer will be "Hello" because the commas were replaced from the
end and the full stops from the beginning.

The default character to strip is white space which can be useful for removing any
white space at the beginning and end of a string value. When removing white
space, there is no need to specify a character.

Remember that the strip function will only strip values from the beginning and
end of a string.

Activity – strip
the final value of fruit in the code below:

fruit = " banana "


fruit = fruit.strip()
print("Of all fruits", fruit, "is my favorite")

the final values of fruit2 and fruit3 below:

fruit2 = " a, x ,, banana b"


fruit2 = fruit2.strip(",x")
print("Of all fruits", fruit2, "is my favorite")

fruit3 = ",,x,,bananab,x,"
fruit3 = fruit3.strip(",xb")
print("Of all fruits", fruit3, "is my favorite")

Write code to strip any punctuation from the beginning or end of a sentence input
by the user.

Extension: use the replace function to strip any punctuation from anywhere in
the sentence.

© paullong.net 2020 Page 46 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net
The split function finds a character within a string and splits the string into a list of
values separated by that character. You will learn more about lists later.

Example – split
The code below will search for commas. It will then create a list of all the values
between the commas.
answer = "One,Two,Three".split(",")

The value of answer will be:


['One', 'Two', 'Three']

The default character to split by is white space.

Activity – split
the final value of x in the code below:

txt = "welcome to the jungle"


x = txt.split()

The split and strip functions are very useful when importing a comma
separated- values (CSV) file to separate values at each comma and to strip the
line breaks to turn the file into a two-dimensional list. You will learn more about
reading CSV files later.

Questions – follow me

1) State the value of <answer> in each of the following sets of code: [4]
a) answer = len("Hello world")
b) answer = "Hello world"[4]
c) answer = "Hello world"[3:5]
d) "Hello world"[-1:]

2) State the value of <race> in the following code: [1]


gender = "Boys"
distance = "400"
event = "Relay"
age_group = "Under 13"
length = len(age_group)
race = gender[0] + distance + event[:2] + age_group[0]
+ age_group[-2:]

© paullong.net 2020 Page 47 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

3) State the errors in the following code: [3]


a) answer = len(54)
b) answer = len(Hello world)
c) answer = "Hello"[5]

4) Write code to find the last 3 characters of any word or phrase input by a user.
[4]

A student’s username is calculated by the last 2 digits of the year they started
school, the first 3 letters of their forename and the first 3 letters of their surname. All
letters must be lowercase. For example, Joseph High who joined the school in 2015
would be 12joshig.

5) Write code to create a student’s username when their first name, surname and
year they joined the school are input. [5]

forename = input("What is your first name? ")


surname = input("What is your surname? ")
year_joined = input("What year did you join the school: ")

username = year_joined[2:4] + forename[0:3] + surname[0:3]

A part number consists of the last digit of the year of manufacture, the first 2
characters of the manufacturer’s name and the last 3 digits of the stock code. All
letters must be upper case.

6) Write code to calculate the part number of a product.

Extension:
A cipher is an algorithm that encrypts text so that it cannot be understood without
the decryption key. A cipher algorithm is used to encrypt a string “This is my
original text”. The cipher algorithm converts each character in the string to its
ASCII code and then adds 4 to that code. Each code is stored in a 6-digit format
using leading zeros when required.

7) a) Write code for the cipher algorithm. [6]


b) Write code for a decipher algorithm to decrypt the encrypted text. [6]

© paullong.net 2020 Page 48 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

5) Programming concepts

Sequence
A computer program can run in sequence – that is from start to finish:

Display
Display “Hello
START “What is your Wait for User Input STOP
<user input>”
name?”

Each instruction takes place in order. If the order is wrong, the program may not
run as expected.

Sleep
The sleep procedure can be used within a sequence of commands to pause a
program. This could be useful to give the impression that something is happening
in the background or to slow down the speed that the computer processes data.

To use the sleep procedure, you will need to import the time library:

import time

You can then specify the number of seconds that you want the computer to
pause for:

time.sleep(seconds)

Example – sleep
The code below asks the user questions and pretends to be able to answer them.
Sleep is used to give the impression that somebody is thinking.
import time

name = input("What is your name? ")


time.sleep(2)
print("Alexa is typing...")
time.sleep(4)
print("Hi", name, "I'm Alexa, your personal assistant.")
what = input("What can I do for you today? ")
time.sleep(2)
print("Alexa is typing...")
time.sleep(3)
print("I'm sorry, I can't do", what)

© paullong.net 2020 Page 49 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Run the code and watch what is happening as you answer the questions.

the code so that Alexa asks and answers more questions.

Selection
Selection is one method of controlling the flow of the program. The idea of
selection is that some program statements will only run sometimes. A question is
asked that requires an answer of true or false and the program will take one of two
different directions depending on the answer.

Assign user’s age


Is <user_age>
START Ask user their age to the <user_age> Yes Status ← “Child”
under 18?
variable

No

Status ← “Adult” STOP

Scratch Link – selection


This Scratch example follows the selection part of the
flow chart above. If the< user_age> is under 18 then
status is assigned the value “Child”, otherwise (else) it
is assigned the value “Adult”.

Selection in programming follows the pattern of:

if condition is true:
run these statements
else:
run these statements

Example – if . . then . . else


The flow chart and scratch examples above in code would be:

user_age = int(input("How old is the user? "))

if user_age < 18:


status = "Child"
else:
status = "Adult"
#endif

© paullong.net 2020 Page 50 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Note: the #endif comment is not required, but it helps to follow code more easily.

It is not always necessary to have an else part to the selection. It is possible just to
have a then part alone:

if condition is true:
run these statements

Example – if . . then

Is <score> higher than Display


START Yes STOP
<high score> “Congratulations”

No

The flow chart above in Python code would be shown as:

high_score = 20
score = int(input("What is the score? "))

if score > high_score:


print("Congratulations")
#endif

Video
Watch the http://tiny.cc/bbcselection from BBC Bitesize and read the example
below the video.

© paullong.net 2020 Page 51 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – if . . then . . else


1) Write code for each of the following flow-charts:
a)

Is <mark>
START Yes Grade ← “Pass” STOP
over 50?

No

Grade ← “Fail”

b)

Is <password> Assign TRUE to


START Yes STOP
= “h0n3y!”? <password_accepted>

No

2) Write code for each of the following algorithms:


a) If the day is “Monday” then display “Weekday”.
b) If the month is “December” then assign True to <christmas_month>
otherwise assign False to <christmas_month>.
c) If a year group is less than 7 then assign “Primary” to <school>
otherwise assign “Secondary” to <school>.
d) If a user’s input is “North” then display “Good Move” otherwise reduce
<score> by 2.

Extension: draw flow charts for each of the algorithms above.

Multiple options
if . . then . . else only allows for two options – a condition is TRUE route and a
condition is FALSE route. This is fine when only two routes are needed, but often
more than one route is needed. For example, you might want to display the name
of the day of the week based on a number from 1 to 5. There are 5 options and so
a normal if . . then . . else will not work.

To do this, elif (else if) is needed:


if condition is true:
run these statements
elif condition is true:
run these statements
elif condition is true:
run these statements
else
run these statements
#endif
© paullong.net 2020 Page 52 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – else if
To determine the day of the week based upon its number:
day_number = int(input("Enter a number for the day of the week
between 1 and 7: "))
if day_number == 1:
day_name = "Monday"
elif day_number == 2:
day_name = "Tuesday"
elif day_number == 3:
day_name = "Wednesday"
elif day_number == 4:
day_name = "Thursday"
elif day_number == 5:
day_name = "Friday"
else:
day_name = "Weekend"
#endif

Scratch Link – else if


This is what else if looks like in Scratch:
This Scratch example assigns different values to the
<status> variable depending on the <user_age>
variable. It starts by checking to see if <user_age> is
less than 2. If it is, then “Infant” is assigned to
<user_age>. It then continues with else if <user_age>
is less than 18 then assign “Child” to <status>. There
is then another else if <user_age> is less than 65 then
assign “Adult” to <status>. Finally, else assign “OAP”
to <status>.

Activity – else if
Write code for each of the following algorithms:
1) Display the words “One”, “Two”, “Three” for user input of numbers 1-3 or “Not
valid” for any other number.
2) In a test, students who score less than 40 will fail. From 40 to 59 is a pass, from
60 to 79 is a merit and 80 or above is a distinction. The score is stored in a
variable named <score> and the grade should be stored in a variable
named <grade>.
3) Display a person’s gender based on the input of their title of Mr, Mrs, Miss or
Ms.
Extension: draw flow charts for each of the above algorithms.

© paullong.net 2020 Page 53 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

You may have noticed that elseif is really just a case of nesting another if block
within the else section. It could also be written like this:

if condition is true:
run these statements
else
if condition is true:
run these statements
else
if condition is true:
run these statements
else
run these statements

Nested selection
Sometimes, another if . . then . . else block needs to be nested inside another IF
block. This is known as a nested IF.

if condition 1 is true:
if condition 2 is true:
run these statements (a)
else:
run these statements (b)
#endif condition 2
else:
run these statements (c)
#endif condition 1

Comments are not needed


but do make the nesting
easier to follow.

This could be represented in a


flow chart like this:

© paullong.net 2020 Page 54 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – nested if
This works out whether a person is a man, woman, boy or girl:

status = input("What is your status (Adult or Child)? ")


gender = input("What is your gender (Male or Female)? ")

if status == "Adult":
if gender == "Male":
description = "Man"
else:
description = "Woman"
#endif
else:
if gender == "Male":
description = "Boy"
else:
description = "Girl"
#endif
#endif

Activity – nested if
Write code for each of the following algorithms:

1) If a sheep is an adult then females are known as ewes and males are known
as rams. Otherwise baby sheep are known as lambs. The variable <adult>
can either be True or False and the variable <gender> can either be “M” for
male or “F” for female. Complete the code in the Python file.
2) Some rubbish can be recycled. If the rubbish is recyclable then if it is paper it
should be put in the paper bin and if it is plastic then it should be put in the
green bin. All other rubbish should be put in the grey bin. The variable
<recyclable> can be True or False and the variable <rubbish_type> can
be “Paper”, “Plastic”, “Nappies” etc. Display the colour of bin that
should be used. Complete the code in the Python file.
3) The user is asked to input two numbers. If <number 1> and <number 2> are
the same, then display “Numbers match”. If <number 1> is bigger than
<number 2> then display “Number 1 is bigger”. If <number 2> is bigger
than <number 1> then display “Number 2 is bigger”.
4) If <input_integer> is 0 then display “Zero”. If it is negative, then display
“Negative” and if it is positive display “Positive”.

Extension: draw flow charts for each of the above algorithms.

© paullong.net 2020 Page 55 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Iteration
Iteration is a posh word for repetition.
In programming, iteration is about
loops. It means that a set of
instructions can be repeated without
writing them out again. Instructions
can be repeated a set number of
times which is known as a count-
controlled loop.

Alternatively, instructions can be


repeated while/until a condition is true.
This is known as a condition-controlled loop.

Note: Edexcel use the wrong terminology for iteration. Iteration actually refers to
any repetition of code using either count-controlled or condition-controlled
loops. Edexcel’s specification wrongly uses the terms repetition and iteration
to mean different things. Edexcel refers to iteration as only meaning
iterating through items in a data structure which is a wrong interpretation.
You should however be aware of Edexcel’s interpretation for the exam.

Video
Open http://tiny.cc/BBCiteration from BBC Byteszie.
1) Watch the video about iteration.
2) Listen to how zoologist Bill Sellars uses controlled loops
3) Read about infinite loops.

With count-controlled loops, the number of iterations (repeats) is known before the
loop starts. For loops are count-controlled loops.

With condition-controlled loops, the number of iterations is NOT known before the
loop starts. The loop will continue while/until a condition is true. The loop will
involve an instruction that assigns a value to a variable that is part of the condition
of the loop. While loops in Python are condition-controlled loops.

For loop
A for loop is a count-controlled loop. It will repeat a specified number of times. In
Python, a for loop will repeat for each item in an iterable (something that can be
iterated). This is particularly useful for lists such as arrays and files which you will
learn about later in this chapter.

As a string is an iterable, it is possible to work through each character in a string.

for character in string:


repeat these statements

© paullong.net 2020 Page 56 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – for each item

This for loop will work with each character in the string named mystring. It will
send each character to the display one at a time and add a hyphen to each
character. The part that is end="" simply stops the console from creating a new
line.

mystring = "Hello World"


for character in mystring:
print(character + "-", end="")
#next character

With <mystring> as "Hello World", the output would be:

H-e-l-l-o- -W-o-r-l-d-

Experiment with different values of mystring and replacing the


hyphen with other characters.

The comment #next character is not needed, but it helps to understand what is
happening with the code.

Activity – for each


Using for loops to iterate through strings, write code for each of the following
algorithms:

1) Display each character of a phrase input by the user, with


each character separated by a comma.

2) Remove any spaces from a phrase input by the user. You will need to use an
if statement within the for loop and assign each character to a new string,
missing out the spaces. Complete the code that has been started for you in
the Python file.

A for loop can also repeat a set number of times. In Python, for loops only work
through each item in an iterable. Therefore, a range of values is created as a list
so that each value in that list can be iterated through.
for variable in range(start, stop):
repeat these statements

Recap on how range works from earlier in this chapter.

© paullong.net 2020 Page 57 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – for loop


The code below generates a range of 5 values [1,2,3,4,5] which will be the list that
the for loop iterates through. The counter variable will take on the value of each
item in the list in order: 1, 2, 3, 4, 5:
for counter in range(1,6):
print(counter)
#next counter

This for loop will repeat 5 times. The variable named <counter> is assigned the
value 1 for the first time through the loop. <counter> then moves through each
value in the list until it gets to 5. This loop will display the numbers 1 to 5 on the
screen:
1 2 3 4 5

In other programming languages, you might see this written as:


for counter from 1 to 5
print(counter)
next counter

This adds one to the value of counter each time and so performs the same job as
working through a list from 1 to 5.

Note: remember that range goes up to but not including the stop value.

Scratch Link – for loop


This Scratch example follows the example above. It displays
“I’m repeating” 5 times.

This can be represented as a flow chart:

The value of counter is


initially set to 1 (first item in
the range),

Then it is displayed on
screen.

It is increased by 1
(incremented by 1) – next
item in the range.

If the counter has become 5


(last item), then the loop
stops.

© paullong.net 2020 Page 58 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – for loop


This is another example of a for loop.
myNewWord = ""
print("Please enter three words. Press enter after each word.")
for counter in range(1,4): #for counter from 1 to 3
myWord = input("Enter word: ")
print("Word number", counter, "is", myWord)
myNewWord += myWord
#next counter

This for loop will repeat 3 times through [1,2,3]. Each time the user will be asked
to input a word. The word is then displayed on the screen together with which
number word it was, using the value of counter:

Word number 1 is Apple


Word number 2 is Banana
Word number 3 is Cherry

The word is also added to a new word so all 3 words appear as one:
AppleBananaCherry

Activity – for loops

1) Modify the code below so that it displays the numbers 11 to 30:


for counter in range(1,21): # 1 to 20
print(counter)
#next counter

Write code for each of the following algorithms:


2) Display the * (asterisk) 10 times.
3) Display the results of the 5 times table from 5 to 50.
4) Ask the user for a number. Display the times table from 1 to 16 for that
number.
5) Display the numbers 5 to 10 on the screen.
6) Display 100 dice rolls for a 6-sided dice.

Extension: draw flow charts for each of the above algorithms.

© paullong.net 2020 Page 59 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

So far, the for loop has had a fixed start number and a fixed end number. It is
possible to replace the start and end numbers with variables.

Example – customised for loop


endnum = int(input("Please input a number: "))
for counter in range(1, endnum + 1): # 1 to endnum
print(counter * 4)
#next counter

This for loop will repeat the number of times decided by the user. The variable
named <endnum> is assigned the number chosen by the user and the loop runs
until it gets to the value of <endnum>. If the user enters the number 6, the following
will be displayed on the screen:
4 8 12 16 20 24

It is also possible to choose a starting number.

Example – customised for loop


startnum = int(input("Please input a start number: "))
endnum = int(input("Please input an end number: "))

for counter in range(startnum, endnum + 1): # startnum to endnum


print(counter * 3)
#next counter

If the user enters the number 20 followed by the number 24, the following will be
displayed on the screen:
60 63 66 69 72

Activity – customised for loops


Using for loops, write code for each of the following algorithms:
1) Ask the user for a start number and an end number. Display all the numbers
from start to end on the screen.
2) Ask the user for a number. Display the * (asterisk) 5 times the number entered
by the user. For example, if the user enters 8, then display the * 40 times.
3) Display the 16 times table up to the maximum factor chosen by the user.
4) Display the results of a times table chosen by the user. The user should also be
asked the maximum factor to use.
5) Ask the user how many random numbers they would like. Display that
number of random numbers between 100 and 500.

Extension: draw flow charts for each of the above algorithms.

© paullong.net 2020 Page 60 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

So far you have seen how the for loop can be used to count one number at a
time. It is also possible to set the for loop to count multiple numbers at a time using
the step option in range:

for variable in range(start, stop, step):


repeat these statements

Example – for step


for counter in range(1, 12, 2):
print(counter)
#next counter

This for loop will start by displaying 1 and will then keep adding 2 until 11 is
reached. It displays all odd numbers between 1 and 11. The output will be:

1 3 5 7 9 11
It is not really the for loop that is adding 2 each time, but the range function which
has created a range from 1 to 11 in steps of 2.

multiple = int(input("Please choose a multiple: "))


start = multiple
end = (multiple * 10) + 1
step = multiple
for counter in range(start, end, step):
print(counter)
#next counter

This for loop will step up in values of the multiple chosen by the user. It will start at
the multiple chosen by the user (e.g. 5) and then keep adding the multiple (e.g. 5)
until it reaches 10 times the multiple’s value (e.g. 50). It displays a times table. If
the user input 5 as <multiple> then the output will be:

5 10 15 20 25 30 35 40 45 50

Activity – for step


Using for loops with range and step, write code for the following algorithms:

1) Display even numbers from 2 to 20.

2) Display the odd positioned characters of “Count every character”. The


output should be “o n v r h r c e”. Tip – you will need to
calculate the length of the phrase.

3) Display multiples of 10 from 10 to 100.

© paullong.net 2020 Page 61 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

While loop
The simplest while loop is one that repeats forever. This flowchart shows a loop that
will never end:

Display “Hmm. . .” Display “Hello” for


START
for 2 seconds 2 seconds

Scratch Link – forever while loop


This Scratch example will repeat forever. The sprite will
think “Hmmm…” for 2 seconds, then say “Hello!” for 2
seconds then repeat the whole process forever.

Example – forever while loop


A loop that continues forever could be useful if programming a sequence of lights
that will keep repeating.

import time
while True:
print("Red")
time.sleep(5)
print("Red/Amber")
time.sleep(1)
print("Green")
time.sleep(5)
print("Amber")
time.sleep(2)
#end while

The example above will continue forever START


because the condition is always true.

However, a condition is normally used at


Is condition
the start to stop the loop from continuing true?
No

forever. If the condition is true, then the


instructions in the loop will run, but if it is Yes
not true then the loop will finish. While
loops are condition-controlled loops. Run Instructions STOP
While loops are known as pre-condition
loops because the condition is tested
before the loop starts. It is possible the
loop may never run if the condition is never true.

© paullong.net 2020 Page 62 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – car accelerator


START To drive a car, a driver needs to put
their foot on the accelerator. This
flow chart starts a while loop by
checking the condition “Is foot on
Is foot on
No accelerator?” If the foot is on the
accelerator?
accelerator, then the car moves
forward and the condition is
Yes
checked again. This keeps
repeating and so the car will
Move car forwards STOP continue to move forward. If the
driver’s foot is not on the
accelerator, then the loop will finish.

The Python code used for a while loop is:

while condition is true:


repeat these instructions

Example – while loop


This WHILE loop checks for an error when data is input.

chosen_number = int(input("Please select a number between


1 and 10: "))

while chosen_number > 10 or chosen_number < 1:


print("Incorrect number!")
chosen_number = int(input("Please select a number
between 1 and 10: "))
#endwhile

While a number that is not between 1 and 10 is chosen, the loop will be run
displaying an error message and asking for a number again. If the user chooses a
number between 1 and 10 straight away, then the WHILE loop will never run.

This while loop displays the real numbers 200 to 100. 5 in reverse order, including
half values:

counter = 200
while counter > 100: Can you code this while loop as a for loop
print(counter) instead? Hint: you will need a negative
value for step and step must be an integer
counter = counter - 0.5
so you will need to divide the output by 2.
#endwhile
© paullong.net 2020 Page 63 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – while loops

1) Complete this code so that it displays “I am good at this” 25 times.


counter = 0
while counter < #a number goes here:
print("#text goes here")
counter = counter + #a number goes here
#endwhile

Write code using WHILE loops for each of the following algorithms:
2) Ask the user for a number. While the number is still at least 1, keep dividing it
by 5. Display the final value of the number.
3) Ask the user for a number. Add up all the numbers between 1 and that
number. For example, if the users gives 4, then add 1 + 2 + 3 + 4.
4) Ask the user for a number between 55 and 65. If the user enters an invalid
(out of range) number then display an error message and ask them to enter a
number again.
5) Ask the user for a password. The password must be “letmein”. If the password
is wrong then inform the user and ask for the password again.

Extension: draw flow charts for each of the above algorithms.

Nested loops
A nested loop is a loop inside another loop. It
START
is possible to have a for loop inside a while
loop or similarly any loop can be nested
inside any other loop.
Is condition
No
1 true?
This example shows a while loop nested inside
another while loop. While condition 1 is true, Yes
the outer loop will run. If condition 2 is also
true, then the inner loop will run repeatedly Run instructions
STOP
in loop 1
while condition 2 is true. When condition 2 is
no longer true, the outer loop will then
Yes
continue until condition 1 is no longer true.
Is condition
2 true?

Yes

Run instructions
in loop 2

No

© paullong.net 2020 Page 64 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – nested loops


for counter1 in range(1,6): # 1 to 5
This nested FOR loop will
for counter2 in range(1, counter1 + 1): display this output:
print(counter1, end="") 1
#next counter2 22
print("\n") 333
4444
#next counter1 55555

The outer for loop above runs 5 times. For the first run through, counter1 has the
value of 1. Therefore, the inner for loop only runs once and displays the value of
counter1 which is 1. For the second run through, counter1 has the value of 2.
Therefore, the inner for loop runs twice and displays the value of counter1 twice.

for counter1 in range(1,6): # 1 to 5


This nested FOR loop will
for counter2 in range(1, 6 - counter1): display this output:
print(".", end="") ....1
#next counter2 ...22
for counter3 in range(1, counter1 + 1): ..333
.4444
print(counter1, end="") 55555
#next counter3
print("\n")
#next counter1

The outer for loop above runs 5 times. The first inner for loop will run the number of
times calculated by 5 minus the value of counter1, which on the first run through
will be 4. Therefore, 4 dots are displayed before 1 is displayed.

Scratch Link – nested loops


This Scratch example draws
the shape shown. It draws 4
octagons because the outer
loop is repeated 4 times. It
draws octagons, because the
inner loop repeats 8 times –
each run through draws a side
and turns 45 degrees.

© paullong.net 2020 Page 65 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – nested loops

1) The following needs to be displayed to the screen:

55555
666666
7777777
88888888

Replace ### in the code below with numerical values and/or variables so that it
displays the above values to the screen:

for counter1 in range(###,###):


for counter2 in range (###,###): # 5 to counter1
print(###, end="")
#next counter2
print("")
#next counter1

Write code using nested loops for each of the following algorithms:
2) Display the following:
1
22
333
4444

3) Display numbers as in 2) but up to the maximum number chosen by the user.


4) Display the results of the 2 times table, 3 times table up to 10 times table.
5) Display the results of times tables up to the maximum value chosen by the
user.
6) Display the results of the times tables from 1 to 10 including the calculations.
For example, 1 x 1 = 1, 1 x 2 = 2, 1 x 3 = 3

Extension: draw flow charts for each of the above algorithms.

© paullong.net 2020 Page 66 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Questions – follow me

1) Examine the Python code below. The user will be asked to input values for x
and y.
A) for a in range(1, 11): print("Yes")
B) while x == y: print("Yes")
C) if x == 5: print("Yes")
D) while x == 4 and y == 5:
print("Yes")
x = int(input("Please input a number: "))

For each question below, choose the most appropriate letter.


a) Which one is a count-controlled loop? [1]
b) Which one is selection? [1]
c) Which one will never display “Yes” when <x> is input as 4. [1]
d) Which one of B, C or D will display “Yes” at least once when <x> is 4 and
<y> is 5?

2) Here is some code used during a game:


if lives > 0:
print("Keep going")
else:
print("Sorry, you have lost all your lives")

a) If the value of <lives> is 5, what will be displayed on the screen? [1]

b) Change one line of code to display how many lives are left. [1]

[ TURN OVER ]

© paullong.net 2020 Page 67 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

3) Line numbers are used for the algorithm below but are not part of the code.

1 value1 = int(input("Please enter number 1: "))


2 value2 = int(input("Please enter number 2: "))
3 while value1 != value2:
4 if value1 > value2:
5 value1 = value1 - 1
6 else:
7 value2 = value2 - 1

a) State the line number where iteration is first used. [1]


b) State the line number where selection is first used. [1]
c) How many lines use variable assignment? [1]
d) In what circumstance would the algorithm finish with <value1> and
<value2> being less than the value they both started with? [1]
e) If the users chooses 5 for <value1> and 20 for <value2>, how many
iterations will there be? [1]

4) Line numbers are used for the algorithm below but are not part of the code.
The algorithm calculates the amount of discount to apply for a holiday.

1 price = float(input("Please enter the price without


discount: "))
2
3
4 discountCode = input("Please enter the discount code: ")
5 if discountCode == "a":
6 discount = 0.1
7 elif discountCode == "b":
8 discount = 0.15
9 elif discountCode == "c":
10 discount = 0.2
11
12
13 discountAmount = price * discount
14 discountedPrice = price - discountAmount
15 print("Discount Amount: £", discountAmount)
16 print("Discount Price: £", discountedPrice)

© paullong.net 2020 Page 68 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

a) Calculate the value of discountedPrice and show your working when the
price and discount code entered are:
(i) 100 and b [2]
(ii) 600 and a [2]

b) Add code to lines 11 and 12 to assign the value 0 to the discount code if
one of a, b or c are not entered. [2]

c) Add code for lines 2 and 3 above to only allow values of a, b or c to be


accepted for the discount code. If another value is entered, the user
should be asked for the discount code again. [3]

Write code for the following algorithms:


5) A user is asked to enter a new password and then asked again to enter it to
confirm it matches. If the passwords match, then the password is assigned to
the variable <good_pass> and the user is told “Password successfully
changed”. If the passwords do not match then the user should be asked to
enter the password twice again until they both match. [5]

6) Ask the user for a number between 0 and 200. If the number is below 50,
display "Too high". If it is smaller than 50, display "Too low". Keep repeating until
the user enters 50. Display how many attempts it took the user to guess the
number.

7) A game of rock, paper, scissors. The computer will ask the user to input “Rock”,
“Paper” or “Scissors”. The computer then randomly generates its own answer
from those 3 options. Paper beats Rock (scrunches it up), Rock beats Scissors
(makes them blunt) and Scissors beat Paper (cuts it up). The computer should
state who won and what the computer chose.

8) A cipher is an algorithm that encrypts text so that it cannot be understood


without the decryption key. Ask the user to input a phrase. The cypher should
dd all the odd positioned characters of the phrase to a new string. It should
then add the even positioned characters to that new string so they appear
after the odd positioned characters.

a) Encrypt the phrase using code with this cypher.


b) Write the code to decipher the encrypted text.

© paullong.net 2020 Page 69 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

6) Operators

Relational operators
Relational operators are used to compare two values. These are the relational
operators and the symbols that you need to be familiar with:

equal to ==
not equal to !=
less than <
greater than >
less than or equal to <=
greater than or equal to >=

Maths Link – relational operators


These statements are all true:

5>3 6 == 6 8 >= 8 9>8 7 != 4

In algebra, numbers can be replaced by letters:

a>5 means that a is greater than 5


c >= 6 means that c is greater than or equal to 6

small < big


When comparing values and variables, it is
important to ensure you use the correct
relational operator. The < and > symbols are

big > small


easily mixed up. Here is a tip to remember
them. The small number goes at the closed
end of the symbol and the big number at
the open end of the symbol.

Activity – relational operators


1) Which of these statements are true?
a) 25 < 23 b) 18 >= 17 c) 79 <= 79 d) 44 < 44

2) If the value of p is 235, which of these statements are true?


a) p != 234 b) p > 236 c) p <= 235 d) p >= 20

Relational operators are used as part of conditions in the control flow of a


program. They are used with IF, WHILE and REPEAT conditions.

© paullong.net 2020 Page 70 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – relational operators in conditions

In the if example below, b is compared with a to see if it is greater than a. Can you
spot anything wrong with the ELSE part?

a = input("What is value of a? ")


b = input("What is value of b? ")
if b > a:
print("b is the bigger number")
else:
print("a is the bigger number")

what the output of the code below will be:

b = 0
while b < 10:
print(b)
b = b + 1
#endwhile

the code – was your prediction correct?

what the output of the code below will be:

c = input("What is value of c? ")


c = int(c)
while c >= 2000:
print(c)
c = c / 2
#endwhile

the code – was your prediction correct?

Scratch Link – relational operator


This Scratch IF block uses the less than
operator (<) to see if the value of the user’s
answer is less than 10. If it is, then it says
“That’s a single digit number”. Otherwise it
says “That number has more than one digit”.

© paullong.net 2020 Page 71 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Logical operators
A logical / Boolean operator returns a response of True or False. They are used in
conditions.
not condition must not be true
and two or more conditions must both be true
or either one of two conditions must be true

Example – Boolean operators


This if statement checks to see if a username and password are both correct:
username = input("Please input username: ")
password = input("Please input password: ")

if username == "Administrator" and password == "letmein":


print("Access Granted")
else:
print("Incorrect username or password")
#endif

The code below will repeat while either condition is true:

p = int(input("Please input a number: "))


q = int(input("Please input another number: "))

while p < 100 or q < 1000:


p = p + q
q = q * 3
#end while

The code below will repeat while both conditions are true:

lives = 3
score = 0

while lives > 0 and score < 10:


answer = int(input("Please input a number between 1-5: "))
if answer == random.randint(1,5):
score = score + 1
else:
lives = lives - 1
#endif
print("score is currently", score)
print("lives is currently", lives)
#endwhile

© paullong.net 2020 Page 72 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Scratch Link – Boolean operators


This Scratch IF block will say “Wrong number,
try again.” if the answer is not 0.

The repeat loop below will continue to move


10 steps until the sprite is touching either the
beetle or the frog.

It is also possible to have a combination of conditions:

Example – combined Boolean operators


The code below will repeat while none of 1, 2 or 3 are entered:
while not (menuchoice == "1" or menuchoice == "2"
or menuchoice == "3"):
menuchoice = input("Please select option from the menu: ")
#endwhile

A neater way of writing this code would be:


while menuchoice not in ["1", "2", "3"]:
menuchoice = input("Please select option from the menu: ")
#endwhile

Activity – Boolean operators


Write code for each of the algorithms below:

1) Ask a user for a password and keep asking for the password while it is not
“letmein”. Do not use the != operator.

2) Display two numbers to the user. Ask the user to multiply them together then
ask the user to divide the first by the second. If both answers are correct
then display “Well done”, otherwise display “Whoops”.

3) Ask the user to enter their gender. If they enter any of “M”, “m”, “Male” or
“male” then display “you must be a man”.

4) Ask the user for 3 numbers - a, b and c. If a is zero or both b and c are 0
then display “You cracked the code”. Keep asking until the code is
cracked.

© paullong.net 2020 Page 73 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Questions – follow me
1) Draw lines to connect the symbols to each relational operation. [6]

a) = greater than
b) > less than
c) <> equal to
d) <= not equal to
e) >= greater than or equal to
f) < less than or equal to

2) Which relational operators should be used in place of ❑ in each example


below? If more than one operator can be used, then list them all. [3]

a) 298 ❑ 300
b) 1,987 ❑ 1,987
c) 565 ❑ 560

3) Describe each of the Boolean operations not, and, or. [3]

4) a) Complete the code below so that it continues until either p is greater than
256 or equal to 256. [1]

p = 1
while p < 256:
print("The next number is", p)
p = p * 2

b) Predict what the output to the screen will be? [1]

© paullong.net 2020 Page 74 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

7) Data structures

Arrays
Earlier in this chapter you learned about how to use variables and set their data
types. A variable can hold a single piece of data. If you wanted to record the
names of several people, you could use variables like this:
name1
name2
name3
name4
name5

Then to collect the data you could assign user input to those variables:
name1 = input()
name2 = input()
name3 = input()
name4 = input()
name5 = input()

This becomes very repetitive. It also only works if you know how many names to
collect and makes it more difficult to process the data stored in the variables

An array is a variable with a single identifier that can hold multiple items of data in
memory. As well as having an identifier name, an array has an index which refers
to the position in the array. Data in an array must all be of the same data type.

Example – array
This array stores people’s surnames. It is called surnames:

surnames = ["Long", "Boden", "Abraham", "Schmidt"]

The array has had 4 values assigned to it which are all string values.

To access these values, the position in the list needs to be identified. The position is
known as the index and starts at 0 (zero).

print(surnames[0]) displays “Long” on the screen


print(surnames[1]) displays “Boden” on the screen
print(surnames[2]) displays “Abraham” on the screen
print(surnames[3]) displays “Schmidt” on the screen

It is also possible to change an individual value in the array by referring to the


index (position).
surnames[1] = "Wheeler"

Note: the index always starts at 0 (unless you are told otherwise).
© paullong.net 2020 Page 75 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net
In the example above, the data can be represented like this:

Position / Index 0 1 2 3
Value Long Boden Abraham Schmidt

The number of items in an array can be found by knowing the length of the array:
number_items = len(array)

Arrays must have data of the same data type (homogeneous). We will look at lists
later which can have data of different data types (heterogeneous). Python
implements arrays using lists.

Activity – array assignment


Write code to assign the first 5 prime numbers to an array and then to display them
on the screen. You do not need to calculate the prime numbers.

The example above assigns values to the array. It is also possible to assign
variables or input values to an array. When accessing or assigning lots of values, a
loop can be used to assign values one at a time.

Example – array for loop


The method in the example above accesses values from surnames but could take
a long time to code, especially if there were more than 4 surnames. The examples
below use loops to access each surname in the array:

for counter in range(0,4): # 0 to 3 (all names)


print(surnames[counter])
#next counter

The variable counter changes in value from 0, 1, 2 to 3 as the for loop runs.

An array is an iterable. It is easier to refer to each item in the array individually by


giving it a name, especially if the number of items in the array is unknown:
for surname in surnames:
print(surname)
#next surname

The example below shows how items in an array can be assigned values using
input from the keyboard:

surnames = [None]*4 # initialises array with 4 values


surnames[0] = input("Please input a surname: ")
surnames[1] = input("Please input a surname: ")
surnames[2] = input("Please input a surname: ")
surnames[3] = input("Please input a surname: ")
© paullong.net 2020 Page 76 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

This can still be inefficient if the number of inputs for the array is not known or if
there are a lot of inputs. Therefore, a for loop or another loop can be used to
cycle through the array using an identifier for the index position:
surnames = [None]*4 # initialises array with 4 values
for counter in range(0, len(surnames)):
surnames[counter] = input("Please input a surname: ")
#next surname
print(surnames)

Input can NOT be achieved using the array (surnames) as an iterable:

for surname in surnames:


surname = input("Please enter surname: ")
#next conter

The reason for this is beyond GCSE level but ask your teacher if you want to know.

Activity – array for loop


1) Complete the code below to use a for loop to assign 5 random numbers to
an array and then to display them on the screen.
import random
rand_numbers = [None]*###
for ### in range(###, ###):
### = random.randint(0, 100)
#next i

2) Modify the code to assign 3 numbers of the user’s choice to an array and
then display the numbers to the screen. You should calculate the length of
the array for the range stop value.

When collecting data for an array, the number of items for input might vary. For
example, the user could be asked how many items they want to input.

Example – input a known quanity


The code below asks the user how many surnames they would like to input. This
response is used to calculate how many times to run through the for loop.
num_surnames = int(input("How many surnames will you input? "))
surnames = [None] * num_surnames

for counter in range (0, num_surnames): # 0 to num_surnames - 1


print("Please enter surname number", counter+1, ": ")
surnames[counter] = input()
#next counter

© paullong.net 2020 Page 77 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net
Another difference between arrays and lists is that arrays have a set number of
items and lists can reduce or increase in size. The append method of lists can be
used to add new items to a list.

The append method looks like this:


myList.append(item)

Example – input a known quantity using a list


The code below does exactly the same as the example above, but instead of
setting the size of the array at the beginning, it creates an empty list and then
appends surname to the empty list.

num_surnames = int(input("How many surnames will you input? "))


surnames = []

for counter in range (0, num_surnames): # 0 to number_surnames - 1


print("Please enter surname number", counter+1, ": ")
new_surname = input()
surnames.append(new_surname)
#next counter

Activity – test scores


Write code to ask the user how many test scores they wish to enter. Then ask the
user to enter each test score. When the user has finished, display each test score
using a for loop.

The user may not know how many data items they are inputting and so could be
asked to input a special character when they have finished.

Example – input unknown quantity using a list


In this example, the user is asked to enter “x” when finished.

while new_surname != "x":


print("Please enter next surname (when you have finished,
enter x): ")
new_surname = input()
surnames.append(new_surname)
#end while
surnames.pop() # remove "x" from the list

Activity – unknown array quantity


Write code to ask the user to enter a list of towns. Tell the user they should enter 0
(zero) when finished. When the user has finished, display each town on a separate
line.
© paullong.net 2020 Page 78 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

It is also possible to search for data in an array. Using a linear search (chapter 1),
each item is checked one at a time until the data being searched for is found or
the end of the array is reached.

Example – linear search of an array


array_name = ["a", "q", "b", "h", "k", "m", "c", "z", "d"]
item_to_find = input("Which letter do you want to find? ")

counter = 0
found = False
while counter < len(array_name) and not found:
if array_name[counter] == item_to_find:
found = True
print("Item was found at position", counter)
else:
counter = counter + 1
#endif
#endwhile

The index (position) of the item being looked for is now known and can be used.

Activity – linear search of an array


what the output of the algorithm below will be:

surnames = ["Long", "Jones", "Harper", "Webb", "Duffy", "Singh"]


search_name = input("Which name do you want to find? ")
counter = 0
found = False
while counter < len(surnames) and not found:
if surnames[counter] == search_name:
found = True
surnames[counter] = input("Please enter new surname: ")
else:
counter = counter + 1
#endif
#endwhile
print("New surnames =", surnames)

You already know how to find the length of an array which will tell you how many
elements there are in it. If an array holds numbers then it is also possible to find the
maximum, minimum and average of all the elements. Python has special
functions to do these, but you could also write your own code to do these.

© paullong.net 2020 Page 79 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – statistical analysis of an array


The following loop calculates the total score from an array:

scores = [14, 15, 19, 14, 9, 8, 20, 12, 17]


totalscore = 0
for score in scores:
totalscore += score
#next score

Each time an element of the array is read, it is added to the total score until all
elements have been added together.

The following loop calculates the minimum score from an array:

min_score = scores[0]
for score in scores:
if score < min_score:
min_score = score
#endif
#next score

Activity – statistical analysis of an array

1) Modify the code from the minimum score example above to find the highest
value in an array.

2) Write code to calculate the average value in an array without using the
built-in statistical functions.

Lists
Lists are very similar to arrays. Python does not use arrays, and so any
implementation of an array in Python is a list. There are two main additional
features of a list:

• a list can change size - items in a list can be added or removed


• a list can include items of different data types

© paullong.net 2020 Page 80 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Some list methods and functions that you will find useful include:

Function / method Purpose Example


list Creates a list structure, myList = list()
including an empty list.
append Adds an item to the end myList.append(item)
of a list.
del Deletes the item found in del myList[index]
the index position.
insert Inserts an item into a list at myList.insert(index, item)
the index position.

Example - lists
The code below creates an empty list:
myList = list()

It is the same as using:


myList = []

The code below will add an item to the end of a list:


myList.append("Mitsubishi")

The content of myList is now:


["Mitsubishi"]

what the contents of myList will be after the following code has run:
myList.append("Volvo")
myList.append("Ford")
myList.append("Vauxhall")

The code below will delete an item from the list:


del myList[2]

what the contents of myList will be after the above code has run.

The code below will insert an item into a list at the index position given:
myList.insert(1,"Toyota")
print(myList)

what the contents of myList will be after the above code has run.

Run your code and see if your predictions were correct.

© paullong.net 2020 Page 81 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – lists
A list contains the numbers below:
myList = [21, 40, 81, 30, 27, 18, 26, 41, 43, 80]

Write code to:


1) Delete 27 from the list.
2) Add 65 to the end of the list.
3) Insert 39 before 81 in the list.
4) Initialise the list so it is empty.

Two-dimensional arrays

Video
Watch http://tiny.cc/arraybbc about arrays from Ed Tracey’s BBC Bitesize videos.

The arrays you have seen so far are one-dimensional because they are a single list
stored in what looks like a single row table:
Position / Index 0 1 2 3
Value 10 20 30 40

Example – two-dimensional array


Consider the railway timetable below:

Station Times
Edinburgh 07:30 12:30 15:30 18:30
Birmingham 10:15 15:15 18:15 21:15
Rugby 11:00 16:00 19:00 22:00
London 11:30 16:30 19:30 22:30

This data could be stored as a two-dimensional array by


identifying the values by their row and column number:

Position / Index 0 1 2 3
0 07:30 12:30 15:30 18:30
1 10:15 15:15 18:15 21:15
2 11:00 16:00 19:00 22:00
3 11:30 16:30 19:30 22:30

The departure time of the 2nd train from Edinburgh is held in position [0,1]. Always
read the row first and the column 2nd.

Note: Although we visualise the data as rows and columns, the computer does
not. We could visualise any of the tables above oriented as columns and
rows instead of rows and columns. So for the departure time of the 2nd train
from Edinburgh, it could also be held in position [1,0] depending on how the
list is structured.
© paullong.net 2020 Page 82 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – array positions


Use the railway timetable stored in the array above. The departure time of the 2nd
train from Edinburgh is held in position [0,1].

1) What time is in each of the following positions?


a) [2][2] b) [3][2] c) [2][0] d) [0][3]

2) Which two-dimensional position would the following times be found in?


a) 07:30 b) 15:15 c) 11:30 d) 16:00

A two-dimensional array is an array of arrays (a list of lists in Python). In the same


way that an array can have a set of numerical or string data, it can also have a
set of array data. Each row is an array within the two-dimensional array. In the
example above, row 0 is an array, row 1 is an array, row 2 is an array and row 3 is
an array. Data in a two-dimensional array would be assigned by using square
brackets within square brackets.

Example – assigning a two-dimensional array


The table below shows exam marks for students. Each student has their results
stored in a separate row:
0 1 2 3 4 5
0 16 30 14 28 23 4
1 30 29 30 28 27 28
2 9 12 8 11 15 7
3 22 24 19 21 18 25

To assign this data to an array, the following code could be used:

marks = [ [16,30,14,28,23,4] , [30,29,30,28,27,28],


[9,12,8,11,15,7], [22,24,19,21,18,25] ]

Notice how each row is included as a separate array with its own square brackets.

Wendy Davies has her marks stored in row 1. Her mark for test 4 is 27. This would
be referenced as position [1,4]. To display this, the following code would be used:

print(marks[1][4])

To enter a new mark for Jennifer Colthup (row 0) in test 2, the following code could
be used:

marks[0][1] = input("Please enter Jennifer Colthup’s mark: ")

When referencing data in an array, use the following syntax:

array_name[row,column]

© paullong.net 2020 Page 83 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

To calculate the length of a row (could be thought of as the number of columns)


within an array, use len for the row:

row_length = len(array_name[row])

To calculate the number of rows within an array, use len for the whole array:

array_length = len(array_name)

Activity – accessing two-dimensional arrays


The following data is stored in a two-dimensional array:

array_tens = [ [1, 2, 3, 4, 5, 6],


[11, 12, 13, 14, 15, 16],
[21, 22, 23, 24, 25, 26],
[31, 32, 33, 34, 35, 36] ]

1) What will be the value of <a> in each assignment below:


a) a = array_tens[0][0]
b) a = array_tens[2][4]
c) a = array_tens[3][0]
d) a = array_tens[0][5]
e) a = len(array_tens)
f) a = len(array_tens[2])

2) Write code to display the following numbers from inside the array:
a) 34 b) 6 c) 22 d) 31 e) 13

3) Write code to change the following data:


a) 36 to 37 b) 14 to 17 c) 4 to 7

4) Write code to ask the user to enter a row number and then a column
number. Then ask the user for a new value. Change the data in the position
chosen by the user to the value chosen by the user. For example, if the user
enters row 0, column 1 and a value of 99 then change 2 to 99.

© paullong.net 2020 Page 84 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

A nested loop can be used to read or write all the data within a two-dimensional
array:

for row in array:


for item in row:
print(item)

The outer loop loops through each row starting with row 0. The inner loop then
displays each data item in each column for the row. The outer loop then moves
onto row 1. This process continues until all rows have been displayed.

Example – looping through an array


The table below shows exam marks for students. Each student has their results
stored in a separate row:
0 1 2 3 4 5
0 16 30 14 28 23 4
1 30 29 30 28 27 28
2 9 12 8 11 15 7
3 22 24 19 21 18 25

To display all marks, the following code could be used:

for student in marks:


print("") # create a new line after the tab
for test in student:
print(test, end="\t") # end with a tab
#next test
#next student

The code end="\t" means that it will separate each item with a tab instead of a
new line. Therefore, to start a new row for each student, a separate print
statement needs adding to print nothing to the screen.

The user could be asked to input marks for each student. First, the array needs to
be created:

num_students = int(input("How many students will you input? "))


num_tests = int(input("How many tests are there? "))

marks=[] # create empty array of marks


for i in range(num_students):
marks.append([None]*num_tests) # create array for each student
#next i

© paullong.net 2020 Page 85 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Once the array has been created, the user can be asked for input of the marks for
each student’s test:

for student in range(num_students):


for test in range(num_tests):
print("Enter mark for student", student, "test", test)
marks[student][test] = input()
#next test
#next student

Run and investigate the example in the Python code file that uses the
list.append() method.

Activity – looping through an array


The following data is stored in a two-dimensional array:
array_cars = [ ["Ford", "B-Max", "Red", "BD43XPU"],
["Volkswagen", "Golf", "Blue", "RX82YHT"],
["Nissan", "Primera", "White", "NS95HDS"] ]

The number of arrays within the two-dimensional array may increase in the future
by using list functions in Python.

Write code to:


1) Display all the data stored in the array using a nested for loop.
2) Display the makes of all the cars. Only display the makes, no other data.
3) Find the length of the two-dimensional array, ask the user for details of a new
car and add a new list to array_cars containing the data for the new car.

4) Find and display the index of the array that has the registration number
“RX82YHT”. Use a while loop.
5) Ask the user for a registration number and then display the data of the car
that has that registration number.

© paullong.net 2020 Page 86 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Records

Note: Python’s use of the term record is different to that used by Edexcel. Edexcel
use the term record to refer to a list which can have values of different data
types as opposed to arrays which can only have values of the same data
type

Edexcel’s definitions are:

Array = homogeneous = sequence of items with the same data type


Record = heterogeneous = sequence of items with different data types

A record stores data about one thing but may have several items of data. For
example:

["Mitsubishi", "Outlander", "2.0", "Petrol", "True"]

A set of records can be stored in a two-dimensional list. For example:

Index 0 1 2 3 4
0 Mitsubishi Outlander 2.0 Petrol True
1 Peugeot 305 1.4 Petrol False
2 Seat Ibiza 1.1 Petrol False
3 Ford Mondeo 1.6 Diesel False

You could visualise this two-dimensional list as a table of records:

Make Model Engine Size Fuel Hybrid


Mitsubishi Outlander 2.0 Petrol True
Peugeot 305 1.4 Petrol False
Seat Ibiza 1.1 Petrol False
Ford Mondeo 1.6 Diesel False

A set of records is a two-dimensional list and so data can be accessed in the same
way as a two-dimensional list.

Example – using records


The set of cars from above can be setup as a two-dimensional list:

cars = [ ["Mitsubishi", "Outlander", 2.0, "Petrol", True],


["Peugeot", "305", 1.4, "Petrol", False],
["Seat", "Ibiza", 1.1, "Petrol", False],
["Ford", "Mondeo", 1.6, "Diesel", False] ]

© paullong.net 2020 Page 87 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

These could then be displayed to the screen using a nested for loop:

for car in cars:


print("\nCar:")
for item in car:
print(item)
#next item
#next car

Predict what the output will look like for each car and then run the code to see if
your prediction was correct.

We could also display each car and refer to what each item means (its field
name):

for car in cars:


print("\nMake:", car[0])
print("Model:", car[1])
print("Engine size:", car[2])
print("Fuel:", car[3])
print("Hybrid:", car[4])
#next car

Predict what the output will look like for each car and then run the code to see if
your prediction was correct.

Often records would look better if they were displayed in a tabular format. We
could use the format function and alignment feature to make the table look neat:

f = "{:<13}{:11}{:^14}{:8}{:7}"
print(f.format("Make", "Model", "Engine Size", "Fuel", "Hybrid"))
for car in cars:
print(f.format(car[0], car[1], car[2], car[3], str(car[4])))
#next car

This is what the output looks like when the code is run:

Make Model Engine Size Fuel Hybrid


Mitsubishi Outlander 2.0 Petrol True
Peugeot 305 1.4 Petrol False
Seat Ibiza 1.1 Petrol False
Ford Mondeo 1.6 Diesel False

© paullong.net 2020 Page 88 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Why do you think the variable f was created? Modify the format code to see how
you could display the data differently. Try displaying the data in a different order
and try missing out some fields (columns).

You may need to search for records which meet certain criteria, for example all
the cars which have an engine size (position 2) bigger than 1.5 litres:
myFormat = "{:<13}{:11}{:^14}"
print(myFormat.format("Make", "Model", "Engine Size"))
for car in cars:
if car[2] > 1.5:
print(myFormat.format(car[0], car[1], car[2]))
#next car

Predict what the output will be for the code above and then run the code to see if
your prediction was correct.

Remember: a record is just a two-dimensional array so you can do anything with a


record that you can do with a two-dimensional array.

Activity – using records


Look at the criminal records stored as a two-dimensional list below:

criminals = [ ["Hamish", "Hamster", 1.65, 7, "Scotland"],


["Jonathan", "Jonno", 1.8, 2, "Wales"],
["David", "Lloydy", 1.78, 24, "Wales"],
["Angus", "Gus", 1.85, "Scotland"]
["Martin", "Coops", 1.72, 4, "England"] ]

1) Someone has attempted to display the data in a table but it has not worked
properly. Modify the code below to show the data in a neater table.

f = "{:<3}{:11}{:^14}{:8}{:7}"
print(f.format("Name", "Alias", "Height (m)",
"Number of Convictions", "Nationality"))
for c in criminals:
print("{:<10}{:14}{:^11}{:8}{:9}".format(c[0], c[1],
c[1], c[4], c[3]))
#next car

© paullong.net 2020 Page 89 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

2) Write code to display just the names of all the criminals who are Scottish.

3) Write code to display the name and nationality of all the criminals with more
than 7 convictions.

Text files

Text files contain plain text and no formatting. They can be used to store data for
use later. In programming, data can be read from a text file and used by the
program, or data from the program can be written to a text file.

Example – plain text file


Open the file called plaintext.txt

A plain text file consists of lines of text. Each line is separated by an end of line
character which is created by pressing the Enter key on the keyboard or by
inserting the ASCII characters 13 and 10 which represent carriage return (CR) and
line feed (LF).
carriage
Carriage return refers to the old days of typewriters
when the carriage would be returned to the
beginning of the line. In computing, carriage
return moves the cursor back to the beginning of
the current line. Line feed moves the cursor down
to the next line but in the same vertical position.
Therefore, the combination of both is to move the
cursor to the beginning of the next line.

Have you ever wondered why the Enter key uses this symbol?

It’s because it creates a LF code and CR code to move the


cursor down a line and return the cursor to the beginning of the
line.
LF

CR

© paullong.net 2020 Page 90 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – end of line


The text file below is the same as the previous one, but the display settings have
been changed to show hidden characters which include CR and LF at the end of
each line:

Normally you would not see the CR and LF codes in a text file.

Lines in a text file do not actually include line numbers as shown above, but a
programming language will refer to each line using a number. The numbering
system starts from 1 (one) rather than 0 (zero) which is a bit confusing when using
files with arrays.

Some text files might contain more than one item of data on each line. This is
often the case when storing files that contain records of data. Each item of data
needs to be separated using a delimiter. A delimiter is any character that is used
to specify where one item of data finishes and the next item of data starts. It
therefore marks the boundary between two data items.

Example – comma-separated values


Open the text file campers.csv which contains data about campers. Each
camper is on a separate line.

Notice how each item of data (e.g. Forename, Surname) is separated by a


comma. This is the most common delimiter used and is used in comma-separated
value (CSV) files. This file can be imported into a spreadsheet and each item of
data will appear in a separate column.

Read a text file


If a text file exists in storage, then its contents can be read by a program.

myFile = open(filename, "r")

The filename refers to the name of the file to open and myFile is the variable
that will refer to the file while it is open. As the file only needs to be read, and not
written to, it can be opened in read-only mode which is indicated by "r".
© paullong.net 2020 Page 91 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net
Once the file is opened, its contents need reading. This can be done one line at a
time or all lines at once. To read a file one line at a time, use:
eachLine = myFile.readline()

If reading one line at a time, Python will read the contents as a single string. If
reading the whole file, then Python will read the contents as a list of strings which
each string being one line.

Example – read a line from a text file


Open the file plain text.txt

To display the first line of the file, use the following code:
plainFile = open("plain text.txt", "r")
firstLine = plainFile.readline()
print(firstLine)
plainFile.close()

This reads the first line from the file called “plain text.txt”, assigns it to a
variable called firstline and then displays it on the screen.

If the file is still open, then more lines can be read. Predict what you think the
output will be for the code below:
plainFile = open("plain text.txt", "r")
myLine = plainFile.readline()
print(plainFile.readline())
plainFile.close()

Run the code and see if your prediction was correct.

the code to read different lines.

The first time readline() is used, it will read the first line. Each time after, it will
read the next line.

Did you notice in the code above that the file was closed when it was finished
with? This will be even more important when it comes to writing files, but it is
always good practice to close the file:

myFile.close()

© paullong.net 2020 Page 92 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

To read all lines of a file, use:

myLines = myFile.readlines()

Example – read a whole text file


To open the file plain text.txt and display all lines, you could use this code:

plainFile = open("plain text.txt", "r")


for line in plainFile:
print(line)
#next line
plainFile.close()

Notice that it was not necessary to use readlines(). This is because a file is also
an iterable. However, if you needed to use the data then it would need assigning
to an array or list. To do this, you could use:

plainFile = open("plain text.txt", "r")


myLines = plainFile.readlines()
print(myLines)
plainFile.close()

Run the code and you will notice that it creates an array of strings with each line
being a separate string in the array. You could display each line in the array using
a for loop:

for line in myLines:


print(line)
#next line

Each string contains an end of line character ("\n"). This can cause problems
when comparing data because "abc" is not the same as "abc\n". The end of
line character can be stripped from each line:

for i in range(0, len(myLines)):


myLines[i] = myLines[i].strip("\n")
print(myLines[i])
#next line
print(myLines)

You read earlier about comma-separated value (CSV) files. These are very useful
because they store data in records and can be imported into a two-dimensional
list.

© paullong.net 2020 Page 93 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – read a CSV file


To open the file campers.csv you could use:

myFile = open("campers.csv", "r")


filedata = myFile.readlines()
myFile.close()

To display all the campers, you could use a for loop:

for line in filedata:


print(line)
#next line

These methods above allow the data to be read, but not used properly or
manipulated. To use the data properly, it needs to be imported into a list. Python
includes a handy CSV library which can be imported. The code below opens the
campers file, recognises the files as comma-separated variables and then imports
the records into a two-dimensional list. Finally, it displays the data.

import csv
myFile = open("campers.csv", "r")
fileReader = csv.reader(myFile)
campers = list(fileReader)
myFile.close()

for camper in campers:


print(camper)
# next camper

Annotate the lines of code above to explain what is happening.

Did you notice that the data included the header row? This can sometimes be
helpful because it means the first record starts at index 1 instead of index 0.
However, it can also become a problem when manipulating the data.

Modify the code so that the header row is removed. Hint: the header row is index
0 and you could use the del function.

Now that you have imported the data into a two-dimensional list, you can display,
search and manipulate it just like you would any two-dimensional list.

© paullong.net 2020 Page 94 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net
The method above uses the CSV library. However, the CSV library is not part of
Edexcel’s programming language subset of Python. Therefore, you need to
understand how to read code that imports a CSV file without using the CSV library.
To do this, two text functions are needed. To remove the line breaks, strip will be
used to remove \n. To separate each line (record) into fields, split will be used
to split the data by commas.

Note: this does not stop you from writing code using the CSV library in an exam
unless the question tells you to not to use any libraries.

Example – read a CSV file manually

The code below will open the campers.csv file and display its contents to the
screen:
myFile = open("campers.csv", "r")
campers = myFile.read()
myFile.close()
print(campers)

what the output will be if you run the following code:


print(campers[2])

Run the code to see if your prediction was correct. You were probably expecting
this to display:
2,Rachel,Larrison,18/07/1954,FALSE,4

but it actually displayed "m". The reason is that the read method above just read
the text as if it was a plain text file into a single string including the commas and
the line break characters. It has not separated this into an array with each line
being a string within the array and it has not separated the data by the commas.
Therefore, the character in index position 2 in this very long string is "m" from "Camper
ID".

One way of separating the single string into a list, is to split the string using '\n' as
the separator:
campers = campers.split('\n')
print(campers)

You will now see that each row is its own string in a list of strings. If we need to get
rid of a header row, then we can delete row 0:
del campers[0] # delete the first row (header row)

© paullong.net 2020 Page 95 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

what the output will be if you now run the code below:
print(campers[0])

run the code above to see if your prediction was correct.

what the output will be if you now run the code below:
print(campers[0][1])

Run the code above to see if your prediction was correct. Were you expecting to
see "Coleman"? The reason you saw " ‘" was because although we have split
each row into an array of strings, it is still a one-dimensional list of strings. Each row
is still a string and not a list of values. The character in index position 1 is a comma.

What we can now do is separate each row into a list of strings for each field. We
can do this by working through each row one at a time using a for loop and
splitting the strings by commas:
for line in range(0,len(campers)):
campers[line] = campers[line].split(',')
#next line
print(campers)

Run the code above and you should see the campers as a two-dimensional list of
lists instead of a one-dimensional list of strings

[['1', 'Coleman', 'Cuneo', '01/08/1997', 'FALSE', '3'],


['2', 'Rachel', 'Larrison', '18/07/1954', 'FALSE', '4'],
...
['40', 'Valentine', 'Granberry', '19/03/2014', 'FALSE', '3']]

This two-dimensional list can now be manipulated like any other two-dimensional
list.

Predict what the pupose is, and what the output will be, for the code below which
filters records:
for camper in campers:
if camper[5] == "3":
print(camper[2])

run the code above to see if your prediction was correct.

© paullong.net 2020 Page 96 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

The example above uses the read method and splits into records by line breaks
and splits into fields by commas. You may also see a method that uses
readlines() which automatically reads the records into a one-dimensional list.
There will still be some work to do to strip the line breaks and split each record by
commas into fields to make a two-dimensional list.

Activity – read a CSV file using readlines


The code below uses the readlines() method to import a CSV file:

myFile = open("campers.csv", "r")


campers = myFile.readlines()
myFile.close()

del campers[0]

for line in range(0,len(campers)):


campers[line] = campers[line].strip("\n")
campers[line] = campers[line].split(',')
#next line

for camper in campers:


print(camper)
#next camper

1) Investigate the code above by annotating comments to explain what each


line of code does.

2) White some code to only display the campers who have a disability.

Activity – read text files


Write code to:
1) Using the file queen address.txt
a) Display the first line of the address on the screen.
b) Display the whole file on the screen.
2) Ask the user for a password. Read the only line of the file password.txt and
check that the password entered by the user matches the password in the
file. Keep doing this until the user gets the password correct.
3) Using the file rooms.csv
a) Read the whole file into a two-dimensional array and then display the
contents of the array on the screen.
b) Remove the header row from the array.
© paullong.net 2020 Page 97 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Write to a text file


Data that has been input by the user or calculated by a program can be written
to a text file. If writing to a text file, any existing data in the text file will be
overwritten. If you need to add data to a text file, then you should append to a
text file.

To open a file to append to it, the code below should be used:

myFile = open(filename, "a")

To open a file to overwrite it, the code below should be used:

myFile = open(filename, "w")

To write a string to a line of a text file, the code below could be used:

myFile.write(data)

In this code, filename is the name of the file and data is the data that will be
written to the file.

Example – write a line to a text file

To save the message “Here is my text” to blank text.txt, use the following code:

myFile = open("blank text.txt", "w") # open in overwrite mode


myFile.write("Here is my text")
myFile.close()

The code above will overwrite any existing text. Modify the code so it writes
different text to the file and watch how the previous text has now disappeared.

The code below will append the data to an existing file so no data will be lost:

myFile = open("more text.txt", "a") # open in append mode


myFile.write("www.gcsecs.org")
myFile.close()

Try running the code above several times and watch what happens to the file
more text.txt.

© paullong.net 2020 Page 98 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

It is also possible to write a list to a text file:

myFile.writelines(list)

Although the name writelines suggests that this would write multiple lines, it just
joins together data in a list to write it to a single line in a text file. It is therefore
necessary to add the line separator symbol \n to each data item.

Example – write multiple lines to a text file


Here is a list of names that we will write to a text file:
names = ["Harry", "Megan", "William", "Kate"]

First, we need to add line separators to the data in our list:


for i in range(len(names)):
names[i] += "\n"
#next i

The list now looks like this:


['Harry\n', 'Megan\n', 'William\n', 'Kate\n']

Now we can open a file in overwrite mode and save the names to the file as
separate lines:
myFile = open("blank text.txt", "w")
myFile.writelines(names)
myFile.close()

Open blank text.txt and check the data has been saved.

If you want to append multiple lines of data, then you need to open the file in
append mode. Modify your code so that it opens in append mode and check
that the names are being added to the file each time.

© paullong.net 2020 Page 99 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – write a line to a comma-separated file


Use the file called campers names.csv

To add a new line of data, we will ask the user to input the data first:
forename = input("Please enter the camper's forename: ")
surname = input("Please enter the camper's surname: ")
dateofbirth = input("Please enter the date of birth: ")

Next we will prepare it in a format that includes the commas and line separator
symbol:
data_for_file = "41," + forename + "," + surname
+ "," + dateofbirth + "\n"

Finally we can append the data to the file:


myFile = open("campers names.csv", "a")
myFile.write(data_for_file)
myFile.close()

Open campers names.csv and check the data has been appended.

The example above works for a single line of text. If multiple lines were required,
then a for loop could be used to write several lines to the CSV file. However,
Python includes a function in the CSV library that takes away all the hard work.

Example – append a list to a comma-separated file


Using the campers names.csv file, we want to add this list to the end of the file:

campersList = [ ["42", "Megan", "Markel", "04/08/1981"],


["43", "Harry", "Windsor", "15/09/1984"],
["44", "William", "Windsor", "21/06/1982"] ]

To do this we can use the writerows function from the CSV library:
import csv
myFile = open("campers names.csv","a", newline='')
fileWriter = csv.writer(myFile)
fileWriter.writerows(campersList)
myFile.close()

Open campers names.csv and check the data has been appended.
© paullong.net 2020 Page 100 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Note: The purpose of newline='' is to avoid having two carriage return (CR)
characters.

Activity – write text files


Write code to:
1) Add “England” to the last line of the file queenaddress.txt.
2) Ask the user for a new password. Replace the only line of
the file password.txt with the new password.
3) Ask the user to enter details of a new room and add those details to a new
line in the file rooms.csv.

Questions – follow me
1) Arrays and records/lists are data structures that can be used in programming.
a) Describe the purpose of an array. [1]
b) Give one reason why lists are sometimes used instead of arrays. [1]

2) Examine the code below:

postcodes = ["W1 1AA", "W1 1AB", "W1 1AC", "W1 1AD", "W1 1AE"]
for position in range(0,5):
print(postcodes[position])

a) Explain why the range for the for loop finishes at 5. [3]

b) What will the output be on the screen? [1]

c) Rewrite the code using for each instead of range. [1]

3) Define the term two-dimensional array. [1]

[ TURN OVER ]

© paullong.net 2020 Page 101 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

4) A list of houses which include the house number, street name and postcode for
each house are stored in a two-dimensional array. A user can be asked for a
postcode, and then the house number and street of all houses with that
postcode will be displayed, e.g. 5a Turtle Grove.

Examine the code below:

houses = [ ["22", "Dolphin Street", "W1 1AA"],


["33", "Whale Circus", "W1 2AA"],
["5a", "Turtle Grove", "W1 3DQ"],
["105", "Octopus Lane", "W2 2BC"],
["45", "Dolphin Street", "W1 1AA"] ]

postcode = input("Please enter a postcode: ")


for position in range(0,5): # 0 to 4
if houses[L1][2] == L2:
print(houses[L1][L3], houses[L1][L4])

a) Which variable should be written at point L1 in the code?


A houses
B position
C postcode
D house [1]

b) Which variable should be written at point L2 in the code?


A houses
B position
C postcode
D house [1]

c) What value should be written at point L3 in the code?


A -1
B 0
C 1
D 2 [1]

d) Which index position be written at point L4 in the code? [1]

e) If the user inputs “W1 1AA”, what will be displayed on the screen? [2]

[ TURN OVER ]

© paullong.net 2020 Page 102 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

5) Students’ test results are stored in a 2D array. Part of the array for 4 of the tests
is shown below:

Students: May Kim Stuart Leo Caleb Naomi


Binary 60 58 42 60 48 40
Logic Gates 25 30 24 32 28 19
Tests

Truth Tables 45 34 46 49 30 31
Networks 42 29 51 35 31 41

For example, Caleb scored 48 in the binary test. There are no half marks.

a) Explain why an array is used to store the data. [2]

b) i) Identify the data type that should be used to store the scores in this
array. [1]
ii) State why this data type is the most appropriate. [1]

c) The code to display the score for Leo in the logic gates test is:

print(scores[3][1])

(i) Write the code to output the score for Kim in the Truth Tables test. [1]

(ii) State the output if the following code is run:

print(scores[4][3]) [1]

(iii) Write an algorithm to calculate the total of all the scores for Naomi.
You must not use any built-in statistical methods or functions. [2]

d) Write an algorithm to display the average score for all students in all tests. [5]

6) Write code to write “I am good at programming” to a new file. [5]

7) Write code to read the whole of the file named trees.csv,


assign the data to an array and display the data on screen.
The file has 50 trees and includes a title row which should
not be included in the array. [4]

© paullong.net 2020 Page 103 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

8) Subprograms (procedures and functions)

Example – making a cup of coffee


There are several stages involved in making a cup of coffee which include:
1) Prepare the kettle
2) Get a cup
3) Add ingredients to the cup
4) Stir the coffee

Each of these stages will involve various steps. For example, adding ingredients to
the cup could include:
a) Add coffee
b) Add sugar
c) Add water
d) Add sugar

Breaking the problem down into groups of steps is known as decomposition. Each
group of steps can then be run together. It is a bit like following a user guide
where instructions are grouped into sections so that you can follow just the
instructions needed.

A subprogram (subroutine) is a block of code that can be executed by calling it


from the program. It is a sequence of instructions to perform a specific task. This is
done by simply writing the name of the subroutine in the program code along with
any parameters that may need passing to it. A subprogram would be equivalent
to the stages in the example above.

In Python, a subroutine is written as follows:


def sub_name(parameters):
# programming code goes here

It is called by writing the name of the subroutine into the programming code,
together with any parameters:
sub_name(parameters)

If no parameters are needed, then empty brackets are used:


sub_name()

When a subroutine has finished executing its code, the program will continue with
the next line of programming code after the subroutine was called:
# programming code run before the subroutine
sub_name()
# programming code run after the subroutine

© paullong.net 2020 Page 104 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

The flowchart symbol for a subroutine is:

Procedures
Procedures and functions are both types of subroutines. Procedures do not return
any data to the programming code but simply run a sequence of instructions. It
helps when following code to prefix subroutines, for example proc_ for procedures.

Example – procedures
Within a program, there are several occasions when a company’s name and
address need to be displayed on the screen. A procedure can be used to
perform this task:
def proc_display_address():
print("Microsoft UK")
print("Microsoft Campus")
print("Thames Valley Park")
print("Reading")
print("RG6 1WG")
#end proc_display_address

Whenever the address needs to be displayed, the subroutine can be called:


proc_display_address()

Whenever this appears in the programming code, it is simpler to understand its


purpose without having to read several lines of code. It also makes the code
easier to read when inside a selection block or iteration block.

Some subroutines are pre-defined within a programming language and are known
as built-in subroutines. An example would be print() which displays data to the
screen. Subroutines that are defined by the user are called custom-made
subroutines.

A subroutine is like a black box – what happens inside is not seen by the rest of the
program. The task is performed and then the program carries on.

Activity – procedures
1) Create a subroutine to ask the user for their name and then to display on the
screen a welcome message to the user.
2) State the identifier you would use to call the subroutine.

© paullong.net 2020 Page 105 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net
A common use of procedures is when a program involves different sections based
upon the options chosen in a menu. The example below shows how this could be
implemented for an ATM (automated teller machine).

Example – ATM menu system


def proc_withdrawal():
print("You have selected withdrawal")
#end proc_withdrawal
The other procedures would be declared in a similar way to the one above.

print("Menu")
print("1 – Cash withdrawal")
print("2 – Balance")
print("3 – PIN Services")
print("4 – Pay bills")
print("5 – Cancel")
user_option = input("Please select an option 1-5: ")

if user_option == "1":
proc_withdrawal()
elif user_option == "2": Predict what will happen if the user inputs 1.
proc_balance()
elif user_option == "3":
proc_pin() Experiment by running the code and
elif user_option == "4": investigating what other options do.
proc_bills()
Try inputting a value that is not 1, 2, 3, 4 or 5.
elif user_option == "5":
proc_cancel()
else:
print("Please only enter an option 1, 2, 3, 4 or 5")
#endif

These procedures could be shown in a hierarchical diagram:

ATM

Withdrawal Balance Pin Bills Cancel

© paullong.net 2020 Page 106 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Parameters
Subroutines can become more useful when they can be used for different values
of data. To do this, data has to be passed into the subroutine. This is done using
parameters.

Example – parameters
The procedure below states how many siblings there are:

def proc_siblings(brothers, sisters):


number_siblings = brothers + sisters
print("You have", number_siblings, "siblings.")
#end proc_siblings

It could be called within a program like this:

bro = int(input("How many brothers do you have? "))


sis = int(input("How many sisters do you have? "))
proc_siblings(bro, sis)

In the example above, the parameters in the main program were bro and sis
which were passed through as brothers and sisters in the subroutine.

Note: Arguments are the actual values that are passed. If the user had input 5 for
bro and 2 for sis then the arguments being passed would have been 5
and 2. In an Edexcel exam you only need to be aware of the term
parameters which will be used to refer to both parameters and arguments.

Activity – parameters
Create a subroutine that displays the name and age of a person on the screen. If
the person is under 18 then they are told they are “too young”.

Functions and return values


Functions are subroutines which can return values to the main program. This
means that a function can perform a calculation and then return the result of the
calculation to the program.

In python, the value to return must be declared using return:

def sub_name(parameters)
# programming code goes here
return result

© paullong.net 2020 Page 107 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – len function


An example of a built-in function in Python is len. This has a single parameter
which is passed into the function and it then returns the length of the value of the
parameter (argument).

length = len(myString)

A function is called by assigning its result to a variable or by using it as part of an


expression. In the example above, the result of the len function is assigned to the
variable length. A function cannot be called by simply typing its name.

Example – functions
This function calculates the perimeter of a rectangle:

def func_perimeter(l, w):


p = (l + w) * 2
return p
#end perimeter

To call the function, the following code could be used:

length = 5
width = 7
perimeter = func_perimeter(length, width)

This function calculates the last position in an array.

def func_array_last(array_name):
last_array_position = len(array_name) - 1
return last_array_position
#end array_last

To call the function, the following code could be used:

scores = [5,8,2,1,9,10,7,6]
last_position = func_array_last(scores)

So far, the examples you have seen are quite simple and only include one or two
lines of code for each function. Functions become particularly useful when they
include several of lines of code and can then be used to represent all those lines
of code in a single word.

© paullong.net 2020 Page 108 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – statistical functions


This function calculates the total of all values in an array. It also calls another
function (array_last) within itself.

def func_array_total(array_name):
array_total = 0
for counter in range(0, func_array_last(array_name) + 1):
array_total += array_name[counter]
#next counter
return array_total
#end func_array_total

This function calculates the minimum of all values in an array.

def func_array_minimum(array_name):
array_min = array_name[0]
for counter in range(0, func_array_last(array_name) + 1):
if array_name[counter] < array_min:
array_min = array_name[counter]
#endif
#next counter
return array_min
#end func_array_minimum

These could be called in a program using an array of scores like this:

total_score = func_array_total(scores)
min_score = func_array_minimum(scores)

Python does already have built-in methods for calculating the total and minimum
values in an array, but these are examples of how they might be implemented.

Activity – functions
1) Create functions (subroutines with return values) for the following:
a) Calculate the area of a circle (use π = 3.14).
b) Calculate the average value in an array.
c) Calculate the maximum value in an array.

2) Write code to call the functions above:


a) Assign the area of the circle to a variable.
b) Display the average and maximum values, written in one sentence.

© paullong.net 2020 Page 109 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – slicing functions


This function can be used to slice a string in the middle. It takes as parameters the
name of the string <string_name> and the <start> character and <end>
character of the slice:
def slice_mid(string_name, start, end):
sliced_string = ""
for position in range (start, end + 1):
sliced_string += string_name[position]
#next position
return sliced_string
#end slice_mid

what the value of middle in the code below would be:

middle = slice_mid("computer", 2, 4)

Run your code to see if your prediction was correct.

if the code below will give the same result? Explain why.

middle = "computer"[2:4]

Investigate how the code within the function works. Annotate each line of code
to explain what it does.

Activity – slicing functions


1) Create functions (subroutines with return values) for the following:

a) Slice a string so a given number of characters at the beginning (left)


are kept. Name the function <slice_left>. It should accept the
string and the number of characters to slice as parameters. For
example, slice_left(“computer”, 4) would return “comp”.

b) Slice a string so a given number of characters at the end (right) are


kept. For example, slice_right(“computer”,4) would return
“uter”.

Activity – read about subroutines


Read http://tiny.cc/subroutines from BBC Bitesize about subroutines.

© paullong.net 2020 Page 110 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Scope of variables
Scope is the extent to which something is relevant. Therefore, the scope of
variables is the extent to which variables are relevant.

When you write a program, any variables declared within the main part of the
program are known as global variables. This means that the variable is available
to every part of the program. The scope is global.

PROCEDURE Main Program PROCEDURE


Local Local
Variables Variables
Global Variables

When you declare a variable within a subroutine, it is known as a local variable.


This means that the variable is only available to that (local) subroutine – it cannot
be accessed anywhere else within the program. The scope is local to that
subroutine only.

This is important because:

global variables declaring variables in a subroutine means that memory


waste memory allocation is only needed while the subroutine is executing
– if the variables were all declared globally, then
unnecessary memory would be used whereas local
variables are removed from memory once the subroutine
has completed
variable names local variables only need to be unique within the subroutine
can be unique rather than throughout the whole program – this means
that a programmer does not need to know the names of
variables used within other subroutines
global variables local variables cannot be changed by another subroutine
can cause bugs which could interfere with the way a program work
local variables start when a subroutine is executed, all local variables are
as null each time added to memory with no data so any previous data from
a previous execution of a subroutine will not affect the
result
global variables because they can be manipulated by multiple subroutines
are hard to trace

Note: it is also possible to have variables whose scope is within a module and are
available to any functions within that module, but not available outside of
that module.

© paullong.net 2020 Page 111 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – scope
The function below uses two local variables (var1 and var2) and returns the new
value of var2 to the main program:

def my_sub(var1, var2):


var1 = var1 * 30
var2 = var2 * 30
return var2
#end my_sub

The code below calls the my_sub function and passes the values 4 and 5 so that
var1 in my_sub starts as 4 and var2 in my_sub starts as 5.

var1 = 2
var2 = 3
var3 = my_sub(4, 5)
var4 = var1 + var2 + var3

what the value of var4 will be.

Run the code to see if your prediction was correct. Experiment with the code to
investigate what is happening at each stage. It will help you to know that the
orange variables above are local variables and the red variables above are
global variables.

© paullong.net 2020 Page 112 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Decomposition and abstraction in programming


Large problems can be solved using a top-down approach. This involves starting
with the whole problem and then breaking it down into more manageable smaller
problems. The process of breaking down the problem is decomposition.

Example – pancakes
Imagine you are going to make some pancakes for Shrove Tuesday. You could
start by separating the problem into 3 main areas:
1) Organise kitchen
2) Make pancakes
3) Serve pancakes
4) Wash up

This could be represented in a hierarchical top-down diagram like this:

Pancakes for
Shrove
Tuesday

Organise Make Serve


Wash up
kitchen pancakes pancakes

Each smaller problem can now be dealt with separately. This means that one
person could organise the kitchen and a different person could do the washing
up.

Each of these smaller problems can be broken down into even smaller problems.
Let’s consider organising the kitchen:

Organise
kitchen

Clean Get Get Put on


surfaces utensils ingredients apron

Now we have even smaller problems. Each of these problems can again be dealt
with separately and so are much easier to solve. The whole problem starts to look
like this:

© paullong.net 2020 Page 113 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Clean surfaces

Get utensils Notice how the “Whisk”


Organise kitchen problem occurs twice and
Get ingredients the “Wash” problem occurs
three times.
Put on apron
These problems only need
Sift salt and flour
solving once and can be
Pancakes for into bowl used many times.
Shrove Tuesday
Break eggs into
bowl

Whisk

Add water and


Make pancakes
milk

Add butter
Get pan to
temperature
Whisk
Pour batter in
Cook
Spread batter to
edges
Fill bowl with
Get crockery
water
Flip
Put utensils in
Get cutlery
water
Serve pancakes
Serve pancake to
plates
Wash The “Cook” problem has
been broken down into tiny
Put crockery in
Wash up
water sub-problems.

Wash

Put cutlery in
water

Wash

© paullong.net 2020 Page 114 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

If a problem can be decomposed into smaller problems using this top-down


approach, then a program can also be decomposed into smaller sections of code
known as subroutines.

Example – draw a stick man


A program could be written to draw a stick man:

Draw body Draw line


Each part of the stick man
can now be dealt with in
Draw circle (head) turn.

Draw circle (eye A separate sub-routine can


left) be written for each part of
the stick man.
Draw circle (eye
Draw head
right)
Some parts use the same
subroutine (e.g. lines and
Draw line (nose)
Draw stick man circles).

Draw line (mouth) The only difference will be


sizes, positions and
directions. These could be
Draw line (left)
specified using parameters
Draw arms as part of the subroutine
Draw line (right) interface.

Draw line (left)


Draw legs
Draw line (right)

Reading the code without knowing the contents of each subroutine, is an


abstraction because the detail of each subroutine is hidden.

© paullong.net 2020 Page 115 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Advantages of subroutines

Main
program

Subroutine Subroutine Subroutine


1 2 3

Subroutine Subroutine Subroutine Subroutine Subroutine


1a 1b 1c 2a 2c

Decomposition Using subroutines means that a top-down design can be


naturally achieved because the main program forms the top of
the tree with each subroutine being a branch of the tree. This
means that each task within the top-down design can be
tackled separately rather than trying to tackle the whole
problem at once.
Abstraction Abstraction removes unnecessary information. With
subroutines, the detail of how each subroutine is removed from
the main program meaning that only the identifier name of the
subroutine needs to be used.
Generalisation Subroutines can be used for a variety of different situations. This
generalises the subroutine so it is not just used once. For
example, a subroutine that finds the average of all values in an
array can be used for any array and not just a specific array
within a program.
Re-usable Subroutines can be used over and over again within a program
and if they are within a module they can even be used in other
programs. This saves having to repeat sections of code as the
subroutine just needs to be called each time instead.
Easier to read It is easier to read the name of a subroutine than all the detail
code involved in how the subroutine works. This makes the code
easier to follow.
Debugging Each subroutine can be tested on its own without being
executed as part of the main program. This means that any
bugs within the subroutine can be corrected before it is tested
within the main program.
Maintenance If code needs to be changed in the future, then it is easier to
change the code within a subroutine rather than having to
work through all the code.
Development It is possible for different people to write the code for each
teams subroutine because each subroutine can exist separately.
Local variables All the advantages of local variables discussed on page 111
apply to subroutines.

© paullong.net 2020 Page 116 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Questions – follow me

1) Examine the code below.

x = 5
y = 6
z = sub_area(x, y)

a) Identify one variable. [1]


b) Identify one subroutine. [1]

2) Examine the code below.

def sub_c(cash):
x = 0
for i in range(1,len(cash)):
x = x + cash[i]
return x

a) Identify one parameter. [1]


b) Suggest a datatype for the parameter. [1]
c) cash is an array of numbers. State the purpose of this subroutine. [1]
d) State one word other than def that shows that sub_c is a subroutine. [1]

3) In programming, variables have a scope.


a) Describe the difference between a local variable and a global variable.
[2]
b) Explain two advantages of using local variables. [4]

4) Subroutines can be used within programming.


a) Other than the use of local variables, explain two advantages of using
subroutines. [4]
b) State the difference between a function and a procedure. [1]

[TURN OVER]

© paullong.net 2020 Page 117 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

5) Examine the code below.

def sub_p(x):
z = x[-1]
return z

a) State purpose of this function? [1]

The main program includes this code:

y = sub_p("Hello")

b) State the value of y? [1]


c) Suggest a more meaningful identifier name for sub_p? [1]

6) A developer has decomposed a problem for the basic operations of an


electronic till in a shop.

Till

Lookup
Calculate
Scan barcodes products and Calculate total
change
prices
The developer is taking a structured approach to developing the solution to
this problem. He wants to implement each sub-problem as a subroutine. Each
subroutine will have its own interface.

a) State two benefits of developing solutions using a structured approach. [2]

The subroutine for calculating the total will include a parameter to receive an
array of the prices that were found when looking up the products and prices.
The subroutine must return the value of the total of all the prices.

b) Create a function that solves this sub-problem. [7]

© paullong.net 2020 Page 118 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

9) Turtle

Turtle is a Python library that can be used to draw on the screen. The library must
be imported using:

import turtle

Moving and turning


The following methods can be used to move and turn the pen:

turtle.forward(n) moves the pen forward n spaces


turtle.backward(n) moves the pen backward n spaces
turtle.left(n) turns the pen direction n degrees to the left
turtle.right(n) turns the pen direction n degrees to the right

Example – turtle moving and turning


The code below can be used to create an equilateral triangle:
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
turtle.left(120)
turtle.forward(100)

This could be implemented in a for loop:

for line in range(0,3):


turtle.forward(100)
turtle.left(120)
#next line

Setting positions
The following methods can be used to change the position of the pen:

turtle.setpos(x,y) moves the pen to exact x and y coordinates


turtle.home() moves the pen to the original starting point (0,0)
turtle.reset() clears the screen, moves the pen to the original
starting point (0,0) and clears all turtle properties

The coordinates 0,0 are in the centre of the Python screen. The x coordinates go
across the screen with positive values to the right and negative values to the left.
The y coordinates go vertically with positive values going up and negative values
going down.

© paullong.net 2020 Page 119 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

y
(-x,y) (x,y)

-x (0,0) x

(300,-75)

(-x,-y) (x,-y)
-y

Activity – turtle setting positions


what this code will do:

turtle.setpos(300, -75)
for line in range(0,3):
turtle.forward(100)
turtle.left(120)
#next line
turtle.home()
turtle.backward(100)
turtle.reset()

© paullong.net 2020 Page 120 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Turtle properties
The following methods can be used to change the properties of the pen:

turtle.hideturtle() hides the turtle icon


turtle.showturtle() displays the turtle icon
turtle.penup() lifts the pen so it can be moved without drawing
turtle.pendown() puts the pen down ready to draw
turtle.pensize(w) changes the width of the pen to w
turtle.pencolor(c) sets the colour of the pen where c is the colour, e.g:
colour name: “red”
RGB value: “#551A8B”
RGB value: (0,35,102)

Activity – turtle properties


what this code will do:

turtle.pensize(20)
turtle.penup()
turtle.setpos(-200, 200)
turtle.pendown()
for line in range(0,5):
turtle.forward(100)
turtle.left(72)
#next line
turtle.penup()
turtle.setpos(200,200)
turtle.pencolor("magenta")
turtle.pendown()
turtle.forward(100)
turtle.hideturtle()

© paullong.net 2020 Page 121 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Questions – follow me

1) The code below will draw a hexagon.

import turtle
turtle.forward(50)
turtle.right(60)
turtle.forward(50)
turtle.right(60)
turtle.forward(50)
turtle.right(60)
turtle.forward(50)
turtle.right(60)
turtle.forward(50)
turtle.right(60)
turtle.forward(50)
turtle.right(60)

a) Modify the code so it uses a for loop to reduce the number of lines of
code. [2]

b) Modify the for loop you have created so it creates a square with red lines
and a line width of 10. [3]

2) a) Write code to ask the user for the number of sides, colour and pen width
to use to draw a polygon. The code should then draw the polygon. [8]

b) Modify your code so that the drawing of the polygon is a procedure


named shape that accepts parameters for the number of sides, colour
and pen width. [5]

c) Test your code by calling the procedure with the following line of code:

shape(10, "brown", 15) [1]

[ TURN OVER ]

© paullong.net 2020 Page 122 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

3) Write code to draw a square house with a triangular roof, 3 square windows
and a rectangular door. Your code should reuse a single procedure for
drawing each window and the house. You should also create a procedure to
draw the roof and another to draw the door. Do not use Python’s built-in turtle
shapes. An example of what your house might look like is shown below:

You should use no more than 15 lines of code in the main program, and each
procedure should have no more than 8 lines of code. [10]

Extension: Create another procedure called window which will accept


parameters for the position of each window so each window will
only require one line of code in the main program. [5]

© paullong.net 2020 Page 123 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

10) Maintainability of code

Once a program has been written and tested, it will be used by the users. During
this time, it may be necessary for maintenance to take place on the code.
Maintenance might be necessary because:
• errors have been found
• a security loophole has been found
• the customer would like some improvements to be made
• the way a business works changes meaning the program needs to change

To carry out maintenance of the code, a programmer needs to be able to


understand the code. It may or may not be the original programmer. Even if it is
the original programmer it may be a long time since they worked with the code
and they are likely to have forgotten what different parts do.

Meaningful identifier names


An identifier is usually a word chosen by the programmer to identify a variable,
constant or subroutine. They are also used in some programming languages to
identify fields, classes, modules, parameters, and units.

The key point is that the programmer decides how to name the identifier. It is very
important that the programmer chooses identifier names that are meaningful and
can be understood throughout the program. For example, using t for telephone
number is not very helpful, but TelNo can be understood by the programmer and
anyone else using the code. There are no golden rules for how to name identifiers
and many languages have their own conventions, but these are some general
guidelines you could follow for good practice:

Use unique identifiers


Each identifier must be unique (different to all other identifiers). It must also NOT be
a standard identifier used for a keyword within the programming language.

Never use spaces


Most programming languages will not allow you to include spaces in an identifier
name and will generate an error. Even if they are allowed, spaces cause
confusion as it can never be clear where an identifier starts and finishes.

When you want to use more than one word for an identifier, you could separate it
with the underscore (_). For example, house_number or end_of_file.

Some programmers use what is known as camel case to separate words. Instead
of using an _ to separate words, they use a capital letter at the beginning of each
new word (except the first word). For example, houseNumber or endOfFile. This is
only possible in languages that allow capital letters. Different languages tend to
have their own conventions. JavaScript programmers tend to use camelCase
whereas PHP programmers tend to use the underscore.
© paullong.net 2020 Page 124 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Prefix the identifier


It can sometimes help to prefix an identifier with a single letter or shortened word
to help remember what data type it is. For example, telephone_number could be
prefixed s_telephone_number or str_telephone_number. Some programmers will
prefix global variables with the word global, for example global_surname. This
helps to track where global variables are being used.

Example – meaningful identifier names

Compare the two algorithms below and predict what each does. Start with the
first algorithm before you look at the second one.

1 print("Hello")
2 x = input("What is your name? ")
3 y = input("How old are you? ")
4 z = yb(y)
5 print(x + ", you were born in " + z)

1 print("Hello")
2 yourname = input("What is your name? ")
3 age = int(input("How old are you? "))
4 YearOfBirth = calculateYearOfBirth(age)
5 print(yourname + ", you were born in " + YearOfBirth)

Run the code and see if your prediction was correct.

The first algorithm is difficult to follow because it is unclear what the purpose of the
function db is and line 5 uses identifier names that do not mean anything to the
programmer.

The second algorithm is much easier to follow as the function is described clearly
using the identifier name and the variables are also clearly identified. Note that
using abstraction, it is not necessary to know how the calculateYearOfBirth
function works.

© paullong.net 2020 Page 125 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Comments
When writing code, it is good practice to add comments to explain what each
part of the code does. This makes it easier for the programmer to understand
what they wrote and why, but also for a future programmer who makes changes
to the code to understand what the program does. It is also good practice to
explain any variables, parameters and return values that are being used.

Example – commented PHP script


This example is for a PHP script to process a form from a web page. As the
language is quite difficult to follow, you will see the importance of the comments
which are preceded by //.

// Its purpose is to process any form and append the form's data
// to a file
// The file is determined by a field (can be hidden) in the form
// called "filename"
// Other fields should be named appropriately for the purpose of
// the confirmation // screen

// Retrieve filename from form


$filename = $_POST['filename'];

// work through each form field


foreach($_POST as $name => $value)
{
// ignore form field if it is Submit or the filename
IF ($value != "Submit" and $value !=$filename)
{
// Add form field to the message to be displayed and a line
// break
$messagedisplay = $messagedisplay . $name. ": " .
$value . "<BR>";
// Add form field to the file to be saved and a comma for CSV
// files
$filedata = $filedata . $value . ",";
}
}

// remove the last comma from the data to be saved


$filedata = rtrim($filedata,",");
// add an end of line character to the data to be saved
$filedata = $filedata . PHP_EOL;
// open the filename with the filename specified in the form
$fs = fopen($filename,a);

© paullong.net 2020 Page 126 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

// write the file data to the file


fwrite($fs,$filedata);
// close the file
fclose($fs);

// Add the introductory information to the message to display


$messagedisplay = "<center><b>Thank you</b><br>Your enquiry has
been sent with the following information:<BR><BR>" .
$messagedisplay . "<BR><BR>and has been saved to " . $filename;

//print the confirmation screen


print $messagedisplay;

The comments help to understand what the code is doing at each stage. Here is
the code without comments – it is much more difficult to work out what is going
on:

$filename = $_POST['filename'];

foreach($_POST as $name => $value)


{
IF ($value != "Submit" and $value !=$filename)
{
$messagedisplay = $messagedisplay . $name. ": " .
$value . "<BR>";
$filedata = $filedata . $value . ",";
}
}
$filedata = rtrim($filedata,",");
$filedata = $filedata . PHP_EOL;
$fs = fopen($filename,a);
fwrite($fs,$filedata);
fclose($fs);
$messagedisplay = "<center><b>Thank you</b><br>Your enquiry has
been sent with the following information:<BR><BR>" .
$messagedisplay . "<BR><BR>and has been saved to " . $filename;
print $messagedisplay;

In Python, the # symbol is used to indicate a line with a comment:


# comments go here

Comments can also be used to temporarily disable a line of code by putting the
comment symbol at the start of the line.

© paullong.net 2020 Page 127 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Use of constants
If a value does not need to change when the programming code is run, then it
can be declared as a constant. For example, the speed of light, π (Pi),

Example – use of constants


Compare the algorithms below:

These algorithms both calculate the area of a circle:

1 radius = int(input("Please enter a radius: "))


2 area = 3.14 * 10**2

1 radius = int(input("Please enter a radius: "))


2 PI = 3.14
3 area = PI * radius**2

In the first algorithm, it may not be clear what 3.14 means, but in the second
algorithm PI is clearly being used.

These algorithms both calculate the time it takes to see light from Mars:

1 timeToSeeLightFromMars = 225000000 / 299792

1 SPEED_OF_LIGHT = 299792
2 AVG_DISTANCE_TO_MARS = 225000000
3 timeToSeeLightFromMars = AVG_DISTANCE_TO_MARS / SPEED_OF_LIGHT

In the first algorithm, it is not clear what the numbers mean in the calculation, but
by declaring them as constants in the second algorithm, it is clear what the
calculation is doing.

Activity – maintainable code


Examine the code below:

ft = int(input("Please enter time taken to fall: "))


df = 9.8065 * ft**2 / 2
print(df)

Improve the maintainability of the code by using a constant and meaningful


variable names.

© paullong.net 2020 Page 128 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Indented code
You may have noticed that gaps have been placed at the left-hand side of
blocks of code. These gaps are known as indents. They help to show the
programmer where a block of code finishes and where it ends. This is important for
debugging and understanding how the code works.

Example – indented code


Here is some code we have seen before:
for student in range(0, number_students):
for test in range(0, number_tests):
print("\nPlease enter mark for student number "
+ str(student) + " test number "
+ str(test))
marks[student][test] = input(": ")
#next test
#next student

The arrows show how the code has been indented to make it easier to follow. The
end of each for block is lined up with the start of the for block it belongs to.
The text to display to the screen is too long to fit on one line so it has been split and
indented to keep it together.

Activity – indented code


Try and explain what the code below does. Then indent it and see how much
easier it is to follow.

status = input("What is the person's status? Adult,


Child or Toddler: ")
age = int(input("What is the person's age? "))
if status == "Adult":
if age > 65:
description = "OAP"
else:
description = "Adult"
#endif
elif status == "Child":
if age > 13:
description = "Teenager"
else:
description = "Child"
#endif
else:
if age > 1:

© paullong.net 2020 Page 129 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

description = "Toddler"
else:
description = "Baby"
#endif
#endif
print("The person is:", description)

Activity – indentation
Find some code you have already written.

1. remove the indentation


2. give it to another student to see if they can understand the code
3. ask the other student to indent the code

White space
When you write a story or an essay, you use paragraphs to separate out sections of
your writing. The same can be done with code. Leaving a line gap between
sections of code makes it more readable.

Example – use of white space


Examine this algorithm for calculating the area and perimeter of a rectangle:

length = int(input("Input the length of the rectangle: "))


width = int(input("Input the width of the rectangle: "))

area = length * width


perimeter = 2 * (length + width)

print("The area of the rectangle is " + str(area))


print("The perimeter of the rectangle is " + str(perimeter))

Notice how line gaps (white space) have been left between the input section, the
calculation section and the output section.

Activity – white space


Find some code you have already written. Add line gaps (white space) to
separate out sections of code. If all your code already has white space, remove
the white space and give it to another student to add in white space at
appropriate points.

© paullong.net 2020 Page 130 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Subroutines
You learned about subroutines earlier in this chapter. Using subroutines makes
code more readable because the detail of each subroutine can be ignored when
looking at the whole program. Subroutines also make the code more
maintainable because each subroutine can be tested individually so it is easier to
find errors.

Many professional programmers will never write more than about 4 or 5 lines of
code at a time. Instead, they will write subroutines which complete small tasks

Example – subroutines
Examine the code below:

usersFileName = "users.csv"
usersList = importUsers(usersFileName)

successfulLogin = False
while not successfulLogin:
username = requestUsername()
password = requestPassword()
successfulLogin = loginUser(username, password, usersList)
#end while

displayMenu()
followMenuOption()

The code uses 6 subroutines. Each subroutine performs a small task. By using
meaningful identifier names for the subroutines, the code is more like pseudo-code
and is very easy to follow. Notice also how white space, indentation and other
meaningful identifier names make the code easy to read. Comments have not
been necessary in this code because it is so easy to understand.

Each subroutine can be tested separately so if there is a bug within a subroutine it


can be easily isolated.

© paullong.net 2020 Page 131 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Questions – follow me
1) Describe three factors you should consider when deciding on an identifier
name. [3]

2) One way of making code maintainable is to use subroutines. State three other
ways in which code can be made maintainable. [3]

3) Explain why it is important that code is maintainable. [2]

4) Examine the code below which gives 2 points if the answer to a question is
correct and 1 point if the answer to a question is incorrect.

def qu(s):
x = input("What is the Capital of France? ")
if x == "Paris":
print("Well done. You get 2 points")
s = s + 2
else:
x = input("Try again: ")
if x == "Paris":
print("Well done. You get 1 point.")
s = s + 1
else:
print("Oops. Wrong answer. You get 0 points.")
return s
total = qu(5)
print("Your total is:", total)

Rewrite the code so it is more maintainable. You do not need to use any other
subroutines. [7]

© paullong.net 2020 Page 132 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

11) Robust and secure programming

Validation routines

Activity - valid
If you were to look up “valid” in a thesaurus, what words would you find?
Spend 1 minute on your own listing similar words.
Now spend 1 more minute with a partner comparing your list and discovering
more words.
Now spend 2 minutes with 3 different people (i.e. group of 4) sharing your list and
discovering new words.
Discuss your findings with your class teacher.

If something is valid, it means that it meets the allowed criteria. A credit card has a
valid from date and a valid to date. That means it is acceptable to use it within
that range of dates. One of the words you may have come up with as a similar
word to valid could be “correct”. However, as you will see later, if data is valid it
does not mean that it is correct.

Validation is a process that takes


place when data is input into a
computer system. As the data is
input, the computer will check to
see if the data is acceptable to the
system. If it is, then the data will be
accepted. If it is not, then the data
will be rejected, an error message
might be shown to the user to tell
them what is wrong and what needs
to be put right, and the user could
be given another opportunity to
enter the data. This reduces data
entry errors but it also prevents
programming code from crashing if
invalid data is input. For example, if
the user is asked to enter some
numbers that will be used in
calculations, but enters text, the
program may crash when it tries to
perform a calculation on text.

© paullong.net 2020 Page 133 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – validation
Copy the database Cleaners.mdb and open it – a form should open.

1) Enter your forename, but leave the surname blank. What happens when
you try to save the record?

2) Now put in your surname, but put tomorrow’s date as your date of birth.
What happens when you try to save the record?

3) Put your date of birth in and enter Y for your gender. What happens when
you try to save the record?

4) Put your gender in and try to enter 90 years of service. What happens when
you try to save the record?

5) Try “d” as the number of years’ service. What happens when you try to save
the record?

6) Put 2 as the number of years’ service and input the NI number as YT821092E.
What happens when you try to save the record?

7) Try different combinations of valid and invalid NI numbers.

There are several different methods that can be used to check data when it is
input. The most common of these are explained below.

Presence check
A presence check simply ensures that some data has been entered for a specific
field. In other words, the field cannot be left empty.

Example – presence check


The surname field must have some data in it.

Long = valid
L = valid
[null] = invalid (null means blank)

In programming code, you can check if the user has entered any data. If they
have not, then they can be presented with an error message and asked to enter
the data.

© paullong.net 2020 Page 134 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – presence check code


The code below keeps asking the user for their surname until the value is not null.
Experiment with inputting null data and some data.

surname = ""
while surname == "":
surname = input("Please enter your surname: ")
#endwhile

The code above did not include an error message. Run the code below to see
how it is easier for the user to understand their mistake:

surname = input("Please enter your surname: ")


while surname == "":
print("\nSurname cannot be blank.")
surname = input("Please enter your surname: ")
#endwhile

Range check
A range check will ensure that data is within an acceptable range. There will be a
lower limit and a higher limit. When you followed through the validation activity,
you attempted to enter a number (90) that was not within the acceptable range
that had been set for the number of years’ service field. The range started at 0
and finished at 25. Any data outside of the range is invalid and will be rejected.

Examples – range check


Number of years’ service >=0 and <=25. This means the data must be at least 0
(i.e. not negative) and a maximum value of 25.

service = int(input("Enter number of years’ service: "))


while service < 0 or service > 25:
print("Number of years must be between 0 and 25")
service = int(input("Enter number of years’ service: "))
#endwhile

Predict what the output will be when the following values are input using the code
above:

-3 0 1 9 24 25 26 80

Run the code and input the values above to see if your prediction was correct.

© paullong.net 2020 Page 135 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – range check

1) Examine the validation routine below:


number_input = int(input("Please enter a number: "))
while number_input <= 6 or number_input >= 11:
number_input = int(input("Invalid. Try again."))
#endwhile

Which of the following data values will be accepted as input?


3 4 5 6 9 10 11

2) Write a validation routine using code to check the input of a person’s age is
at least 18.

Length check
A length check ensures that data is a minimum, maximum or specific length. Only
data that meets the length requirements will be accepted.

Examples – length check


This validation rule ensures the number of characters in a surname is at least 2. If
only one character is entered, then it will be rejected.

surname = input("Enter your surname: ")


while len(surname) < 2:
print("\nSurname must be at least 2 characters.")
surname = input("Enter your surname: ")
#endwhile

This validation rule ensures a telephone number is at least 6 digits long and a
maximum of 15 digits long:

telephone = input("Enter your telephone number: ")


while len(telephone) < 6 or len(telephone) > 15:
print("\nTelephone number must be between 6 and 15
characters long.")
telephone = input("Enter your telephone number: ")
#endwhile

Experiment with different lengths of surname and telephone number. Try to see if
you can find the shortest and longest surnames and telephone numbers that can
be input.

© paullong.net 2020 Page 136 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – length check


Write a validation routine using code to check the input of a product code is
exactly 5 characters long.

Type check
A type check will check to see that the data is the correct data type. Only data
of the specified data type will be accepted. This would usually be tested using a
function. In Python, these functions include:

input_string.isdigit() # True for digits 0-9 only


input_string.isnumeric() # True for digits from any language
input_string.isalpha() # True for letters a-z and A-Z
input_string.isalnum() # True for a-z, A-Z and 0-9
input_string.isupper() # True for A-Z in UPPER case only
input_string.islower() # True for a-z in lower case only

Each function returns a value of True if the criteria are met and False if the
criteria are not met.

The difference between isdigit and isnumeric is very subtle. isdigit will
return True if only digits 0-9 are in the value. isnumeric will also return True for
digits 0-9 but will also return True for characters from other languages such as
Chinese and for Unicode fractions, subscript numbers and superscript numbers.
isalpha will also return True for foreign alphabetical letters.

When you followed through the Validation Activity and tried to enter “d” as the
number of years’ service, it was rejected because it was not an integer data type.

Examples – type check


This code checks to see if input data is a positive integer (digits 0-9 only):

price = input("Please enter price: ")


while not price.isdigit():
print("Price must be a positive integer.")
price = input("Please enter price: ")
#endwhile

This validation routine deliberately receives the price from the keyboard as a
string. If it tried to receive the price as an integer and a string was input it would
crash the program rather than giving a helpful error message.

Experiment with different numbers including positive integers, negative integers,


and real numbers (with decimal point).

© paullong.net 2020 Page 137 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – type check


1) Complete the table below showing whether True or False would be
returned for each value using each type check:
isdigit isnumeric isalpha isalnum isupper islower
235
124.28
£81
Hello
STOP True
BD62ZPU False
2ndPlace
2nd Place False
¾
england False

二 is the Chinese symbol for the number 2.

2) Examine the validation routine below.

number_input = input("Please enter a number: ")


while not number_input.isdigit():
print("Invalid, please try again.")
number_input = input("Please enter a number: ")
#endwhile

Which of the following data values will be accepted as valid input?


23 -21 4.56 Matthew 0 One

Pattern check
A pattern check will ensure that data entered matches a specific format. When
you tried to enter different types of National Insurance numbers in the cleaners
database, it would only accept data that matched the following pattern check:

• First two characters must be letters


• Characters 3 to 8 must be digits
• Character 9 must be a letter between A and D

The type check functions can be used to test individual characters within an input
string.

© paullong.net 2020 Page 138 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – pattern check


This code checks that a product code has 3 digits, followed by 1 uppercase letter
and 2 lowercase letters. A

valid = False
while not valid:
product = input("Please enter product code: ")

# check for the length of 6 characters


if len(product) == 6:
valid = True

# check for the digits


if not product[0:3].isdigit():
valid = False
print("First 3 characters must be digits")
#endif digit

# check for the uppercase letters


if not product[3].isupper():
valid = False
print("4th character must be uppercase")
#endif upper

# check for the lowercase letters


if not product[4:6].islower():
valid = False
print("Last 2 characters must be lowercase")
#endif lower
else:
valid = False
print("Product code must be 6 characters long")
#endif len
#endwhile

Experiment with different values for input, including both uppercase and
lowercase characters.

© paullong.net 2020 Page 139 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – pattern check

1) Using the pattern check in the example, which of the following product
codes are valid and which are invalid?

12B345cd 307Bdp 822ruy 91Pew 242Tqa 974ecB

2) Examine the validation routine below.


valid = False
while not valid:
classroom = input("Please enter classroom number: ")
if len(classroom) == 2:
valid = True
if not classroom[0].isupper():
valid = False
#endif
if not classroom[1].isdigit():
valid = False
#endif
else:
valid = False
#endif
if not valid:
print("Invalid classroom number.")
#endif
#endwhile

a) Explain what this validation routine does.

b) Which of the following data items are valid for the routine above?
B4 4B B44 44B BB44 44BB b4 4b b44 44bb

3) Write a validation routine using code to check that a single lowercase letter
has been input.

Extension: Write a validation routine that checks a password includes at least


one lowercase letter, one uppercase letter and one number and is at
least 6 characters in length.

© paullong.net 2020 Page 140 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Lookup check
A lookup validation checks to see if the data entered exists in a list.

Examples – lookup check


This code checks that an A Level grade is A, B, C, D, E or U. A function has been
created that will check an array of values.

grades_list = ["A","B","C","D","E","U"]
grade = input("Please enter grade: ")
while grade not in grades_list:
print("Grade must be A-E or U")
grade = input("Please enter a grade A-E or U: ")
#endwhile

Experiment with different values for input, including both uppercase and
lowercase characters.

The example above uses data that is defined within the code. It is also possible to
check a list that is stored within a file, but that is beyond GCSE level. If you want a
challenge though, you could try writing a subroutine that checks if data input exists
within a list stored in a file.

Activity – lookup check

1) Examine the validation routine below.

letters = ["X", "Y", "Z"]


letter = input ("Please enter a letter: ")
while letter not in letters:
letter = input("Invalid. Please try again: ")
#endwhile

Which of the following data values will be accepted as input?


a A b B c C x X y Y z Z

2) Adapt the validation routine above to check the input of a person’s gender
is M or F. The code should accept accidental lowercase input and change
it to uppercase.

3) Write a validation routine to check the input of a person’s title is Mr, Mrs, Miss
or Ms.

Extension: Write a validation routine to check that a value in a file exists.


© paullong.net 2020 Page 141 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Accuracy
The purpose of each validation method described above is to reduce input errors
by identifying invalid data at the point of data entry. This means that when data is
input, if it is invalid then it will be rejected. However, this only ensures that valid
(reasonable) data is accepted and invalid data is rejected. What happens
though if valid data that is incorrect is accepted?

Example - accuracy
In this example, only “M” for male or “F” for female are allowed to be entered. This
is what happens when the following data is entered:

Bobby is a boy. “M” is entered. Valid, so accepted.


Sharon is a girl. “F” is entered. Valid, so accepted.
Roisin is a girl. “T” is entered. Invalid, so rejected. User tries again.
Alex is a boy. “F” is entered. Valid, so accepted.

But Alex is not female. So why has the data been accepted? The reason is
because the data is valid. The system is only checking that the data matches the
rules. It is therefore possible that data that matches the rules, but is incorrect, can
be accepted. This means that it is not possible to use validation to ensure that
data is accurate and so there is no certainty of accuracy.

© paullong.net 2020 Page 142 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Authentication routines
Authentication is the process of checking that a user is who they say they are. I
could turn up to a computer and pretend to be Theresa May and if no password
or other authentication method is required then my logon will be accepted.

Example – simple authentication routine


This is a simple authentication routine that uses a username and password that are
hard coded within the programming code.

authenticated = False
while not authenticated:
username = input("Enter username: ")
password = input("Enter password: ")
if username == "LongPA" and password == "letmein":
authenticated = True
print("Welcome.")
else:
print("Username and password not recognised.")
#endif
#endwhile

Experiment by inputting both correct and incorrect combinations of usernames


and passwords.

Usernames and passwords are usually stored in an encrypted file. For the purposes
of GCSE, we will store a username and password in a plain text file.

Example – authentication from file


In this case, the username is stored on line 1 and the password on line 2 of a file
called user.txt. The code from the example above has been included in a
subroutine named check_pass.

userfile = open("user.txt", "r")


fileUser = userfile.readline().rstrip('\n') # removes line break
filePass = userfile.readline().rstrip('\n') # removes line break
userfile.close()
check_pass(fileUser, filePass)

© paullong.net 2020 Page 143 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

In reality, there will be more than one username and each user will have their own
passwords.

Example – multi-user authentication


This time a CSV file called users.csv is used to store the username and password.
The username is the first item on each line and the password is the second item on
each line.

usersFile = open("users.csv", "r")


users = usersFile.readlines() # read the contents of the file
usersFile.close()

for line in range(0,len(users)):


users[line] = users[line].strip("\n") # remove the line breaks
users[line] = users[line].split(',') # split by commas

authenticated = False

while not authenticated:


username = input("Enter username: ")
password = input("Enter password: ")

for user in users:


if username == user[0] and password == user[1]:
authenticated = True
print("Welcome.")
break # exit for loop as user found
#endif
else: # for
print("Username and password not recognised. Try again.")
#next user
#endwhile

Experiment by inputting both valid and invalid combinations of username and


password. Try adding new users to the file and see if they are accepted.

© paullong.net 2020 Page 144 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Questions – follow me
1) Identify, describe and give an example of a validation rule that could be used
on the field “Transmission” for a vehicle which can be “Manual” or
“Automatic”. [3]

2) Identify, describe and give examples of two different types of validation rules
that could be performed on GCSE Grade (1-9). [6]

3) Look at the form at http://www.paullong.net/training/. Describe using


examples, 4 different types of validation that could be performed on 4
different input fields. [8]

4) Using an example, explain why a length check validation can provide no


certainty of accuracy. [3]

5) Examine the code below:

children = int(input("Please enter number of children


in a class: "))
while children < 5 or children >= 30:
children = int(input("Invalid number of children,
try again."))

State the type of validation check being performed by this routine. [1]

[TURN OVER]

© paullong.net 2020 Page 145 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

6) Examine the code below which authenticates a user.

authenticated = [A]

while [B]:
[C] = input("Enter username: ")
password = input("Enter password: ")
if username == "LongPA" and [D] == "letmein":
authenticated = [E]
print("Welcome.")
else:
print("Username and password not recognised. Try
again.")

Write down the code that should exist at each position:


[A] [B] [C] [D] [E] [5]

7) Write a validation routine using code that checks the presence of a postcode.
If there is no postcode, an error message should be displayed and the user
should be asked to enter it again until one is entered. [5]

8) A National Insurance number must consist of two upper case letters followed
by six numbers followed by one letter between A and D. Complete the code
below to check a National Insurance number is valid. [8]

def checkNI(_________):
valid = _________
length = len(niNumber)

if ______ == 9:
if niNumber[0:___].isalpha():
if niNumber[-1].upper() in ["A","B","C","D"]:
if niNumber[____:____].isdigit():
valid = True
return ______

© paullong.net 2020 Page 146 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

12) Errors

An error in a program is often called a Bug. Bugs cause a program not to run as it
was intended. A bug is usually an error in the programming code.

There is a myth that Grace Hopper first used the term ‘computer bug’
when she discovered a moth in a Harvard University calculator in
1945. It is true that she found a moth, but it was not the first time the
word ‘bug’ had been used for an error. The word ‘bug’ referring to
faults can be traced back as far as Thomas Edison in 1878. Thomas
Edison invented the light bulb.

Activity – finding errors


Examine the code below (line numbers are not part of the code):

1 print("Welcome"
2 name = input(Please enter your name: )
3 age = input("Hello + name + how old are you?")
4 newage = age + 10
5 print("In 10 years you will be", age "years old)
6 while age < 100
7 age = age + 1
8 year = year + 1
9 #endwhile
10 print("You will be age 100 in", years, "time)

Identify the errors within the code. Check your errors with another student.

Debugging is the process of detecting, locating and correcting errors.

Video - debugging
Watch http://tiny.cc/bbcdebugging from 1:39 to 3:46 about how a tester finds
errors in computer games.

Watch http://tiny.cc/debugerrors to see how everybody will find errors in their


code and how to debug them in 4 easy steps.

Syntax errors
Syntax refers to the rules a programming language. Computers can only follow
the instructions given. If the instructions are spelt incorrectly or don’t follow the
rules of the programming language, then the code cannot be understood by the
computer.

© paullong.net 2020 Page 147 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Example – syntax error in English language


Read the following sentence:

“When i grow up? I want be a computor programmer;”

This includes several syntax errors, including:

• i instead of I
• ? instead of , (comma)
• “be” instead of “to be”
• computor instead of computer
• ; (semi-colon) instead of . (full stop)

Common syntax errors in programming include:


• missing an opening or closing bracket
• missing a quotation mark
• not closing a block of code (eg loop)
• spelling a keyword incorrectly
• using capitals instead of lowercase
• using = instead of == when comparing values (language dependent)
• missing part of a block of code
• incorrect number of parameters for a subroutine
• missing a colon at the end of a line (Python)
• inconsistent indentation (Python)

If the code cannot be understood by the computer then it cannot be run.

Example – syntax errors


Missing bracket: x = (a + b) * c - d)
print("hello world"
Missing quotation mark: print(hello world)
Keyword misspelling: pint("hello world")
Using capitals wrongly: Print("hello world")
Using = instead of == if x = 5:
pass
Missing a colon: while x < 5
a = a * 4
print(a)
Missing part of a block: if x == 5:
Incorrect number of parameters for subroutine:
len(myword, 4)

© paullong.net 2020 Page 148 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Logic errors
Logic errors cause a program to give unexpected results. The code can be
understood and can be run, but the output is not what was expected.

A common logic error is to miss the brackets in a calculation.

Example – missing brackets

To calculate how much travel expenses and employee should be paid, the
number of miles travelled should be multiplied by the mileage rate. Examine the
code below and predict what the value of expenses will be:

endMileage = 100
startMileage = 90
mileageRate = 0.45
expenses = endMileage - startMileage * mileageRate

This will not stop the program from running. However, the answer it gives will not be
what is expected. It will actually calculate:

expenses = endMileage - (startMileage * mileageRate)

It should have been written like this:

expenses = (endMileage - startMileage) * mileageRate

Run the code to see how different answers would be given for each attempt.

Another common logic error is to write a condition incorrectly.

Example – conditional errors


If somebody is aged 18 or over, they are classified as an adult and if they are
aged 2 or over, they are classified as a child. Children under 2 are classified as
infants. Examine the code below:

age = int(input("How old are you? "))


if age > 18:
status = "adult"
elif age == 2:
status = "child"
else:
status = "infant"
#endif
© paullong.net 2020 Page 149 of 154 by Paul Long
The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

what will be the value of status for someone aged exactly 18?

This will give incorrect results. If somebody is aged 18, they will not be classified as
an adult. This should have been written as:

if age >= 18:


status = "adult"

Activity – conditional errors


1) Examine the code in the example above.

a) What status would a 5-year-old have?

b) Explain how this logic error has occurred.

c) Rewrite the algorithm above so that it works as intended.

2) A thermostat checks the temperature of a room every 5 minutes. If the


temperature reaches 20 degrees then the heater should be turned off. If
the temperature falls below 20 degrees then the heater should be turned
on.

a) Explain the logic error in the algorithm below:

while True:
temperature = int(input("What is the temperature? "))
if temperature == 20:
heater = "On"
else:
heater = "Off"
#endif
print(heater)
time.sleep(30)
#endwhile

b) Rewrite the algorithm above so that it works as intended.

In all the examples of logic errors above, the program would still run, but it would
give unexpected results.

© paullong.net 2020 Page 150 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Runtime errors
A runtime error causes a program to crash when it is running. This can happen if a
loop runs infinitely.

Example – infinite loop


x = 2
while x != 20:
x = x * 3
print(x)
#endwhile x will never be 20 because 20 is not a multiple of 3.

A runtime error could also cause a program to run out of memory. If a recursive
algorithm never stops, then the computer will eventually run out of memory.

Example – out of memory


There is nothing to stop this recursive function call.

def multiply(x):
x = x * 5
print(x)
multiply(x)
#end multiply

Other runtime errors include:


• accessing an item that does not exist in an array (e.g. item 5 if there are only
4 elements)
• accessing a file that does not exist
• dividing by zero

Testing is necessary to find logic errors and runtime errors. By selecting appropriate
test data and running a range of tests, it is likely that logic errors and runtime errors
will be found. However, some errors may not be found until the program has been
operational for some time and so software patches are needed to fix them.

Activity – types of errors


Examine the errors you found in the finding errors activity.

Identify which errors are logic errors and which errors are syntax
errors.

© paullong.net 2020 Page 151 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Note: The incorrect use of age as both a string and integer would be classed by
some scholars as a syntax error and others as a logic error and others as a
runtime error. Similarly for the use of years instead of year. Some scholars
say that a logic error will never give an error message during run-time and
only runtime errors will allow a program to compile and run, but generate an
error during run-time.

Video – error types


Watch http://tiny.cc/errorsbbc from Ed Tracey’s BBC Bitesize videos.

Watch http://tiny.cc/errortypes about different types of error.

Activity – program sabotage


Open a program which you have created. Deliberately introduce about 5 errors
to your code. Some should be syntax errors, some should be logic errors and some
should be runtime errors. Ask another student to find the errors. The other student
should find the errors, identify the type of errors and fix the errors.

Interpreting error messages


When compiling or interpreting a program, error messages may appear. These will
vary depending on the language being used and the Integrated Development
Environment (IDE) being used.

Example – runtime error


This program should add 6 to a number input by a user:
x = 6
y = input("Please input a number: ")
z = x + y
print("Total =", z)

It will run successfully to start with and the user is asked to input a number:

However, because Python accepts user input as a string, a runtime error occurs
when the integer (6) is added to the string (“5”).

© paullong.net 2020 Page 152 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Activity – runtime error


The error in the example above can be eliminated by casting the string input to an
integer.

x = 6
y = int(input("Please input a number: "))
z = x + y
print("Total =", z)

However, this could cause a new error.

1) Explain the new error that could happen.


2) Explain how this new error could be avoided.

3) Amend the code to avoid this new error.

Activity – debugging
Examine the common error messages presented by Outwood Academies Trust at
http://tiny.cc/debugpython

Using a program you have written before, introduce an error into it. Try to predict
which error message will appear. Repeat this for different errors.

Some IDEs will report errors at the time of writing the code. It’s worth using a good
IDE for programming because they will include features such as:

Colour coding Different colours used for commands, strings, numbers,


comments and errors.
Real-time error Like a spell checker, the IDE will highlight any syntax errors at
checking the time the code is written rather than waiting until the
program is translated.
Bracket The IDE will automatically insert closed brackets for every
matching open bracket. It will also do the same for speech marks.
Auto-complete When typing a command, the IDE will suggest which
command it might be. The IDE can also suggest which
variable could be used.
Parameter The IDE can prompt the programmer as to what parameters
prompts are needed for a subroutine.
Auto indentation Programming code will be indented automatically when a
new code block is started.

© paullong.net 2020 Page 153 of 154 by Paul Long


The Ultimate GCSE CS Textbook for Edexcel - Chapter 6 - Published by paullong.net

Questions – follow me
1) An error is detected while a program is being executed.

a) Name the type of error that causes an error message while a program is
being executed. [1]

b) Name a type of error that prevents a program from being executed. [1]

2) A credit card can be used to pay for goods and services. It will have a limit
which cannot be exceeded. For example, if a person has a limit of £7,000 and
has already spent a balance of £6,900, then they can only spend another £100
before they reach their limit.

The function below is used when an attempt is made to pay by credit card:

1 def checklimit_correct(balance,payment,limit):
2 if balance + payment <= limit:
3 return "Payment confirmed"
4 else:
5 return "Payment declined"

The algorithm contains two errors. Identify the line number of each error, give
the type of error and show the corrected code for that line. [6]

3) During the development of a program, a programmer attempts to find a


number (x) to the power of another number (y). The code used is shown
below:

1 x = int(input("Input first number: "))


2 y = int(input("Input power: "))
3 # calculate x to power of y
4 answer = y**x
5 print(answer)

The programmer tests the code and inputs the value 2 for x and 3 for y. The
programmer is expecting the value of answer to be 8.

a) State the actual result for answer when the code is run. [1]
b) Explain why the actual result does not match the expected result. [2]
c) State the type of error that has caused this. [1]

d) Correct the error in the program. [1]

© paullong.net 2020 Page 154 of 154 by Paul Long

You might also like