LBOA 2.01 web ebook
LBOA 2.01 web ebook
Some Rights Reserved. "The Little Book of Algorithms 2.0" is licensed under a Creative
Commons Attribution - NonCommercial - ShareAlike 4.0 International License.
Attribution — You must give appropriate credit, provide a link to the license, and indicate if
changes were made. You may do so in any reasonable manner, but not in any way that
suggests the licensor endorses you or your use.
NonCommercial — You may not use the material for commercial purposes.
ShareAlike — If you remix, transform, or build upon the material, you must distribute your
contributions under the same license as the original.
ISBN: 978-1-9161163-4-4
Twitter: @MrLauLearning
I dedicate this book to my colleagues and students at Central Foundation Boys’
School. You have to be brave to choose (to teach or learn) computer science; it
is not easy and it is not for the faint- hearted!
To Lloyd, Leila, Jaime, Gavin and the brave computer science students at CFBS -
this is for you
Preface…………………………………………………………… 3
1. If Statements: Lowest number…………………...……. 7
2. String slicing and concatenation……………………… 17
3. Area of a circle………………………………….……………. 21
4. Modulo: Odd or even………………………………….…... 25
5. For Loops………………………………………………….……. 29
6. While Loops……………………………………………………. 30
7. Unlimited pin attempts…………………………………... 31
8. Basic login system………………………………………..... 32
9. Lowest number in a list…………………………...……... 37
10. Linear search…………………………………………………. 38
11. Total of a list..….….………………………………………….. 49
12. Linear search in a 2D list…………………………….….. 53
13. Total of a 2D list…..…………………………………………. 57
14. Login system by reading a file…………………………. 65
15. Writing a list to a file……………………………………….. 69
16. Adding to a list in a file……………………………………. 70
17. Converting binary to denary…….………………………. 75
18. Converting denary to binary…….………………………. 76
19. Solutions………………………………………………………… 89
20. Further reading………………………………………………. 116
21. Acknowledgements…………………………………………. 118
22. Space for further practise and notes….……………. 119
This book is designed to help teachers and students build fluency in their
Python programming. It is aimed at students who have already been
introduced to the three basic programming constructs of structured
programming, namely sequence, selection and iteration. The original aim
was to help my Year 11 students with their GCSE Computer Science
programming exam. However I hope many students and teachers will find
this book useful. The algorithms are represented using Python as this is a
popular language with a low threshold for learning.
I was inspired to write this book after reading articles by Scott Portnoff,
Sue Sentance and Richard Pawson; three luminaries in the world of
computer science education. All three have made me ask the question,
"Why is learning programming so difficult?"
Like many readers, I too found programming challenging and I am still
learning! After teaching programming for the past seven years, I noticed
that only a minority of my students felt confident enough to program
independently after two years of instruction. Upon realising this, I knew I
had to change my pedagogy.
I believe Scott Portnoff is correct; students do need to memorise some
key programming constructs e.g. if statements, while loops and for loops.
This will decrease cognitive load and enable students to practise more
fluently. Portnoff’s work was my starting point for this book. As a student
of b-boy and hip-hop culture, I came across Joseph Schloss’s book
Foundation where he writes about a musical canon that exists for b-boys.
To add to this theory, Jonathan Sacks argues that a literary canon is
essential to a culture. In linking these three ideas together, I thought
about creating a canon for programmers. Perhaps there is a set of
programs which represent algorithms that every computer science
student should familiarise themselves with?
I started to compile a list of programs based on my experience as a
teacher and examiner. Many of the shorter programs are worth repeating
until they are committed to memory and I admit that learning some of the
longer programs by heart is both challenging and futile. Therefore, to
help you develop fluency, I have also written some challenges based on
3
this canon. These challenges should help you understand these
programs by applying them.
Sue Sentance suggested in her introduction to programming courses,
that we should introduce students to subroutines in their very first
program. Richard Pawson goes one step further in edition 07 of the Hello
World magazine; here Pawson puts forward a case for teaching using the
functional programming (FP) paradigm from the outset. He makes a
strong case for using functions which return values rather than
containing inputs and outputs. This seems counterintuitive due to the
perceived complexity of FP syntax, however there are three key
arguments for using functions- unit testing of individual functions, code
reusability, and a separation of concerns. I would therefore encourage
readers to write with functions from the very beginning. This seems
daunting at first, however repetition will lead to fluency.
Despite the irrefutable advantages of FP, I have to be pragmatic and will
include procedures (subroutines which do not return values) and also
programs which do not use subroutines at all. Whilst, I recognise this
might be a step away from the FP paradigm; students are likely to
encounter simple imperative programming questions up to at least GCSE
level. Not including examples of both imperative programming and FP
paradigms would be doing our students a disservice. For some
algorithms, the exclusion of functions also reduces complexity and
cognitive load therefore providing a shallower learning curve.
In order to keep programs as short as possible and to improve
readability, comments are not generally provided in the programs.
Instead, a more detailed explanation is explained below each program. In
lessons, I have found it useful to go through one or two algorithms at the
front of the book with my students and then go on to apply this to the
associated challenges. Alternatively, students may choose to work
through the book independently in class or at home.
This book will hopefully help you to practise and develop fluency in your
programming. Learning programming is similar to learning a musical
instrument. Both involve practise and making lots of mistakes. Both
also require perseverance to develop fluency. Keep going!
4
5
Teaching, like software development and learning is about refinement. In
this new version there are two key changes.
Firstly, challenges now directly follow each relevant skill. This reflects the
structure of most mathematics textbooks and workbooks. It means
there’s less time and effort spent flicking backwards and forwards.
Secondly, there are a greater number and range of challenges because
you will become a better programmer and computer scientist by solving a
greater number and range of problems.
While answers remain in the back of the book, I have also started
creating walkthrough video solutions to some of the more complex
challenges. These are available on Youtube at: https://bit.do/LBOAVids
6
A program which takes two numbers as inputs and outputs the
smallest number.
You may even be asked to write simple programs like this in your
exams. However, good programmers write code which can be
reused and tested in isolation (known as unit testing). Therefore,
using a subroutine (also known as a subprogram) to create a
procedure would produce a "better" program that is modular:
1 def lower_num(num1,num2):
2 if num1 <= num2:
3 lowest = num1
4 else:
5 lowest = num2
6
7 print("The lowest number is " + str(lowest))
8
9
10 first_num = int(input("Enter the first number: "))
11 second_num = int(input("Enter the second number: "))
12
13 lower_num(first_num,second_num)
¹ Arguments and parameters should have different names even if they seem to serve the
same purpose. In this case both num1 and first_num store the first number. However, the
argument stored in the variable first_num has global scope, it can be accessed and
changed anywhere in the program. The parameter num1 has local scope, it is a local
variable which can only be accessed in the subroutine.
8
Write a subprogram that has three parameters, num1, num2 and
num3. The program should take three numbers as arguments and
return the highest number.
def highest_number(num1, num2, num3):
9
Complete the program below which asks the user to enter three
integers and then calls the highest_number subprogram from
the previous page. The returned value is stored in a variable called
highest and then output as a meaningful message
highest = highest_number( )
10
Complete the subprogram below. The subprogram has a parameter
called num which takes a number as an argument and returns a
subject. These numbers correspond to the following subjects:
1 Computer Science
2 Music
3 Dance
4 PE
If the student passes any other value into num, it should return
"Error"
def options( ):
if num == 1:
return "Computer Science"
elif num == 2:
return "Music"
11
Write a program which calls the subprogram options from
Challenge 2. A user should be prompted to enter a number to
choose a GCSE option. The program should then output a
meaningful confirmation message based on the user’s input.
12
Q1) State the output for the following program when the program is
run four times with four different inputs:
num_in Ouput
8 8
3
12
5
1 def mystery_number(num):
2 if num < 5:
3 print(8)
4 elif num < 3:
5 print(8)
6 elif num == 3:
7 print(3)
8 else:
9 print(num)
10
11 num_in = int(input("Enter a number: "))
12 mystery_number(num_in)
Q2) In the program above, four lines of code are redundant i.e. they
can be removed without affecting the program's output, which four
lines can be removed:
Q3) Lines 6 and 7 state that when the number 3 is passed in, the
output should be 3. However, this does not work, explain why:
13
Re-write the program from the previous page so that the program
outputs 1 if the value of num is 3. It should output 8 if the number
is less than 5 (but not 3). It should output the number entered for
all other cases.
14
Parson’s puzzles are named after Dale Parsons1. To solve the
puzzle, re-arrange the code blocks into the correct order. The
subprogram should take two numbers as arguments and subtract
the smallest number from the largest. The result is returned.
num1_in = int(input("Enter a number"))
A num2_in = int(input("Enter a number"))
C return out
D else:
out = num2 - num1
Correct order:
¹Keen students may think that there is a misplaced apostrophe here. However, in
Parsons’ original paper co-authored with Patricia Haden in 2006, they are referred to as
"Parson’s puzzles". Some refer to them as "Parsons problems" or simply "Parsons".
15
Circle the correct answer to the questions below.
16
A subprogram which outputs a username based on a student’s
first name, surname and year of enrolment.
E.g. Connor Pearce 2019 should return 19CPearce.
17
If you wanted to use this user_name procedure later to generate
an email address, this would not be possible without duplication of
code, it is therefore wise to rewrite this subprogram as a function.
This is shown below:
1 def user_name(forename, last_name, year):
2 username_out = year[2:4] + forename[0] + last_name
3
4 return username_out
5
6
7 def main():
8 first_name = input("Enter your first name: ")
9 surname = input("Enter your surname: ")
10 year = input("Enter the year you joined the school: ")
11
12 gen_user_name = user_name(first_name, surname, year)
13 print("Your user name is " + gen_user_name)
14
15
16 if __name__ == '__main__':
17 main()
The main function above spans lines 7-13. Lines 16-17 ensure that
your main function will be the first function to be run when the
program is executed. __name__ == '__main__' by default.
However, if the program is imported, the __name__ value
becomes the module name, so you can selectively run or test
functions. This is yet another advantage of using the functional
programming paradigm.
18
Write a subprogram that takes three strings as arguments: a first
name, a middle name and a last name. The program should take
these three arguments and return only the first letter of each string
thereby generating initials.
return
19
On school timetables, subjects are often shortened to their first 3
characters e.g. Maths becomes Mat, French becomes Fre and
Music becomes Mus.
20
A subprogram which calculates the area of a circle.
21
Write a subprogram that takes the length, width and height as
arguments and return the volume of the cuboid.
After writing the function, show how you might call the function to
output an answer with a meaningful message.
22
Write a subprogram called add which has two parameters, num1
and num2. The two numbers that are passed in should be added to
each other and returned to the user.
total = add(num1_in,num2_in)
23
Circle the correct answer to the questions below.
4) What is a constant ?:
A. A variable which stays the same whilst the program is running
B. A value which can not change whilst the program is running
C. A numerical value
D. Part of a formula which is defined
24
A subprogram which checks if a number is odd or even. It will print
a meaningful message accordingly. The program should loop until
the user enters the sentinel value "STOP"
25
The Odd or Even program could be improved by using a function
instead of a procedure. Re-write the program so that all inputs and
outputs take place outside of the is_odd function. You could also
use a main function as shown previously on page 23.
26
Given that we can use MODULO to see if there is a remainder, we
can write a subprogram which tells us if a given number x is a
multiple of y.
is_multiple (x_in, ):
if == 0:
print( )
else:
27
While % (MODULO) returns the remainder from a division. We can
also do Integer division, also known as floor division or DIV by
using // . Using // ignores any remainder and always rounds down.
1) State the output for the following program when the program is
run four times with four different inputs:
29
A program which generates a random number then asks the user
to guess the random number. The program repeats until the
correct number is guessed.
As we do not know how many guesses the user will need to guess
the number correctly, we use a while loop (also known as a
condition-controlled loop). It is an indefinite loop.
1 import random
2 randomNumber = random.randint(1,10)
3 guess = 99
4 while guess != randomNumber:
5 guess = int(input("Guess the number between 1 and \
10: "))
6 if guess == randomNumber:
7 print("Correct")
8 else:
9 print("Try again")
30
A program which allows the user to enter a pin number. If the user
gets the pin number wrong, the program keeps asking them to
enter a correct pin.
The program keeps looping while the pin is not equal to 1984. It
is very similar to the program on page 11.
Line 1: Sets an initial value that is not equal to the pin. This
ensures the while loop runs at least once.
Line 3 asks the user to enter their pin.
Lines 5-8 check to see if the pin matches, a meaningful
message is produced depending on the outcome.
31
A program which checks to see if the username and password
matches the one in our program. The user gets three attempts.
1 username = "James"
2 password = "myPasswordIsDog!"
3 pass_in = ""
4 tries = 0
5
6 while tries < 3 and pass_in != password:
7 user_in = input("Enter the username: ")
8 pass_in = input("Enter the password: ")
9
10 if user_in == username:
11 if pass_in == password:
12 print("Logged in")
13 else:
14 print("Incorrect password")
15 else:
16 print("Incorrect username")
17
18 tries = tries+1
The program below should ask the user for a word and keep asking
for words until the characters "XXX" are entered. "XXX" acts as a
sentinel value or rogue value which stops a loop from running.
When the sentinel value is entered, the program should stop asking
for words and an acronym should be generated and output
print( )
33
The previous acronym generator program is inefficient as the user
has to enter each word separately and has to enter a sentinel
value.
N.B. in the program below we can iterate through each word in the
words string by using the line for word in words:
This means the same as
for count in range (len(words)):
acronym = ""
words = input("Enter words to be turned
into an acronym")
#Convert words into a list of indivudal words
words_list = words.split()
#For each word in the words_list
34
Write a program which simulates two dice being rolled. Output the
values of both dice. Keep prompting the user to roll the dice until
the two dice match e.g. Double 6. When the user roles a double,
output the message "Game loading". For all other combinations,
ask the user to press Enter to roll again.
35
Write a program which simulates two dice being rolled three times.
Output the total value of both dice for each roll. Keep track of the
score over 3 rounds and output the total at the end
Hint: As we know that the pair of dice are rolled three times, this
repetition is fixed. We therefore need to use a count-controlled loop i.e. a
for loop.
36
A program which iterates through a list of numbers and outputs the
lowest number
1 numbers_list = [9,8,7,5,6,2,1,12,14,0,13]
2
3 lowest = numbers_list[0]
4
5 for count in range(len(numbers_list)):
6 if numbers_list[count] < lowest:
7 lowest = numbers_list[count]
8
9 print("The lowest number in the list is ", lowest)
37
Iterating through a list from start to finish as seen in the previous
algorithm is effectively a linear search. We start at position 0 and
continue checking each position from left to right until we reach the
end. A meaningful message informs the user whether the item was
found.
1 def linear_search(target):
2 names = ["Elizabeth", "Samuel", "Jawwad",
3 "Yacoub", "Cara", "Jess",
4 "Benji", "Thamber", "Suki", "Zi", "Q"]
5
6 found = False
7
8 for count in range(len(names)):
9 if target == (names[count]):
10 print(target, "found at position", count)
11 found = True
12
13 if found == False:
14 print(target, "was not found")
15
16
17 name = input("Who are you looking for? ")
18 linear_search(name)
39
Re-write the program from the previous page as a subprogram. The
list of numbers should be passed in as an argument. The
subprogram should then iterate through a list of numbers and
return the highest number
40
Write a program which asks the user to enter a desired password.
Perform a linear search through a list of obvious weak passwords.
If the user’s password is found in the obvious passwords list,
output a message to tell them it is weak and would be easily
hacked using a brute force attack.
41
Add in various validation checks to the program on the previous
page. One example might be a length check, so if the password
does not meet a particular length it is also declared weak. Other
checks could be a presence check and format check. The format
check could check to see if the user entered any numbers, symbols
and a mixture of upper and lower case letters. Meaningful
messages are necessary for each different validation check.
42
Write a program which simulates a penalty shootout. The computer
is the goalkeeper and dives a random direction or stays in the
centre each turn. The keeper’s move is generated but not
outputted at first. The user takes a penalty by typing in "left", "right"
or "centre". The keeper’s move is then outputted. If the player
typed left and the keeper dives left, the penalty is saved etc. The
program repeats 5 times. After 5 penalties, the winner is
announced with a meaningful message.
Hint: Pages 29 and 30. I strongly advise using a pencil for this one!
import random
x y
0
1
1 y = 0
2
3 for x in range(0,4):
4 if x % 2 == 0:
5 y = x + 2
6 print(y)
47
Circle the correct answer based on the following code:
import random
for count in range(0,5):
num1=random.randint(1,10)
2) What are the first and last values of count if they were
outputted?
A. 0 and 5
B. 0 and 4
C. 1 and 5
D. 1 and 4
48
A program which adds up numbers in a list
1 number_list = [9, 8, 3, 5, 4, 1, 8, 4, 1]
2
3 total = 0
4
5 for count in range(len(number_list)):
6 total = total + number_list[count]
7
8 print("The total sum of the list is ", total)
Write the main function which contains your list and which calls the
subprogram (function)
50
Iterate through the sentence below and count how many times
each vowel occurs. At the end of the program, ouput the number of
As, Es, Is, Os and Us with a meaningful message.
def vowel_counter(sentence):
A = 0
E = 0
I = 0
for
if sentence[ ].upper() == "A":
51
52
A program which searches for a student’s results within a 2D list of
exam scores.¹
1 cs_scores=[["Jo","45","60","72"],["Zi","55","65","70"],
2 ["Ellie","71","78","78"],["Jessica","68","79","80"],
3 ["Taseen","65","70","71"]]
4
5 print("We will try to find the result for a given \
student's exam")
6
7 name = input("Enter a student name: ")
8 exam_number = int(input("Enter the exam number: "))
9
10 found = False
11
12 for count in range(len(cs_scores)):
13 if name == cs_scores[count][0]:
14 found = True
15 result = cs_scores[count][exam_number]
16 print(name+ "'s result for exam", exam_number,\
"was", result )
17
18 if found == False:
19 print(name, "cannot be found")
¹Python does not have an array data structure. Instead it uses a list. The main differences
between a list and an array is that lists allow the storage of mixed data types and they are
dynamic (allow appending). I’ve tried to use single data types with the lists in this book so
they appear more like arrays. I have also avoided the use of in-built list functions. This
may seem strange and inefficient in places but it has been done as the GCSE exam will
only feature arrays.
53
An A-Level student wants to find out how many marks are required
to receive a certain grade. Write a subprogram that takes a user’s
desired grade as an argument and then iterates through the 2D list
to return the number of marks they need for that grade.
def ( ):
grades = [ ["A*", "90"], ["A", "83",],
["B", "72"], ["C", "60"], ["D", "49"],
["E", "30"] ]
54
Use a 2D List to improve challenge 29; keeping track of how many
times each vowel occurs in the sentence below. At the end of the
program, ouput the number of As, Es, Is, Os and Us with a
meaningful message.
55
56
A program which adds up each student’s scores in a 2D list i.e. a
row or sub list
1 cs_scores = [["Karman","45","60","72"],
2 ["Daniel","55","65","70"],
3 ["Parker","71","78","78"],
4 ["Jessica","68","79","80"],
5 ["Edie","98","85","91"]]
6
7 total = 0
8 for student in range(len(cs_scores)):
9 for exam in range(1,4):
10 total = total + int(cs_scores[student][exam])
11 print("Total for",cs_scores[student][0],"=",total)
12 total = 0
57
Write a program which will output the total for each exam with a
meaningful message.
Hint: As the focus is on each exam rather than each student, the
outer for loop will be for each exam. Remember to reset the total
after each iteration of the inner loop.
cs_scores = [["Karman","45","60","72"],
["Daniel","55","65","70"],
["Parker","71","78","78"],
["Jessica","68","79","80"],
["Edie","98","85","91"]]
total = 0
58
Write a program that outputs the mean average for each student.
cs_scores = [["Theo","45","60","72"],
["Angharad","55","65","70"],
["Sameer","71","78","78"],
["Adrian","68","79","80"],
["Ayana","98","85","91"]]
59
60
Re-write challenge 33 so that it is a subprogram. The subprogram
should take the 2D list of exam results as an argument and output
the mean average for each student.
cs_scores = [["Theo","45","60","72"],
["Angharad","55","65","70"],
["Sameer","71","78","78"],
["Adrian","68","79","80"],
["Ayana","98","85","91"]]
61
62
1) Write the values of x and y for the first 5 iterations of the
program below:
x y output
0
63
Circle the correct answer based on the following code:
for x in range(0,3):
for y in range(2,5):
z = x + y
print(z)
64
A procedure which performs a linear search on a 2D list that is
stored in a file.
users.txt
[['lauw', 'insecurePwd'], ['vegaj', 'iLoveWebDesign'],
['lassamil', 'zeroDawn']]
1 def login():
2 username = input("What is your username")
3 password = input("What is your password")
4
5 newfile = open("users.txt","r")
6 users_2D = eval(newfile.read())
7 newfile.close()
8
9 found = False
10 for count in range(len(users_2D)):
11 if username == users_2D[count][0]:
12 found = True
13 if password == users_2D[count][1]:
14 print("logged in")
15 else:
16 print("incorrect password")
17 login()
18
19 if found==False:
20 print("Invalid username")
21 login()
22
23 login()
users.txt
[['LauW', 'insecurePwd'], ['VegaJ', 'iLoveWebDesign'],
['LassamiL', 'zeroDawn']]
def generate_username(firstname, lastname):
username =
users_file = open( , )
usernames = eval( )
users_file.close()
if == username:
username =
return
66
Write a program which asks for a teacher’s first name and
surname. Then demonstrate how you would call the function on the
previous page to generate a username and output this in a
meaningful message.
The next pages is provided so that you can practise Challenge 37 again
without the writing frame. It’s important that you keep challenging
yourself and eventually you should be able to write these programs
independently.
67
Write a subprogram which generates a username for a teacher
based on their first name and surname. The format should be their
surname, followed by the first letter of their first name. The
program should check to see if the username already exists in
users.txt and if so, a unique username should be generated by
appending a "#" symbol. E.g. if a teacher joins the school called
Winnie Lau, their username would be LauW# . The username
should then be returned.
users.txt
[['LauW', 'insecurePwd'], ['VegaJ', 'iLoveWebDesign'],
['LassamiL', 'zeroDawn']]
68
File writing is essential if you want to save data permanently to
your programs. This allows you to open a program and read in
data. Examples of data might be a shopping list, usernames and
passwords, player names and scores. The program below asks a
user for shopping list items to be written to a file.
Line 2: Sets a default or initial value for item. This allows the
while loop on line 4 to run at least once
Line 3: Creates an empty list which will append to on line 8
Lines 5-6: Allows the user to keep entering items and casts their
item to title case i.e. capital letter on the first character.
Lines 7-8: Checks if the item is "End" and if not, it appends the
item to the items list.
Line 9: Opens a file in write mode. If one does not exist, it will
create a new file. If it already exists, it will overwrite the content.
Line 10: Writes the list as a string into newfile.
N.B. You can only write strings to files, so lists have to be cast.
69
On the previous page, we learnt that opening a file in write mode
will erase the previous data if the file already exists. There are two
ways of adding to an existing file. However, when we are dealing
with lists in Python, the best approach is to read in a list from the
file, append to the list and then overwrite the file with this updated
list. This is shown below.
Shopping_list.txt
[‘Rice’, ’Ackee’, ’Peppers’, ’Tomatoes’]
1 def add_shopping():
2 item = ' '
3 file = open("shopping_list.txt","r")
4 items = eval(file.read())
5 file.close()
6
7 while item != 'End':
8 item = input('Enter a shopping list item or \
9 enter "End" to finish your list.').title()
10
11 if item != 'End':
12 items.append(item)
13
14 newfile = open("shopping_list.txt","w")
15 newfile.write(str(items))
16 newfile.close()
17
18 add_shopping()
We have only changed lines 3-5, these open the file in read mode
and evaluates the contents into a list called items.
If you have paired sets of data e.g. player names and scores or
usernames and passwords, you may want to use a 2D list in a file. The
rest of the code stays the same. However, it’s worth noting that storing
the password as plaintext may be fine for GCSE Computer Science, but in
real applications, it is a really bad idea! Curious readers should visit:
http://bit.do/hashing-python-passwords for more info.
70
Write a subprogram to allow a teacher to register a new account.
The subprogram should take the username and password as
arguments and write these details to the existing users.txt file
shown opposite.
users =
new_user = []
new_user.append(username_in)
users.append(new_user)
users_file = open( , "w")
.write(str( )
71
users.txt
[['lauw', 'insecurePwd'], ['vegaj', 'iLoveWebDesign'],
['lassamil', 'zeroDawn']]
72
1) To append to the end of a file we should use?
A. file.append("some text")
73
Solve the puzzle by re-arranging the code blocks into the correct
order. The program should ask for a user’s e-mail address and if it
is in the 2D list stored in the file, it returns True otherwise it returns
False.
C file.close()
E return Found
if email == users[count][0]:
F found = True
return Found
G found = False
Correct order:
74
A subprogram which takes a 4-bit binary string as an argument and
returns the denary equivalent
1 def binary_to_denary(binary):
2 bit1 = int(binary[3])*1
3 bit2 = int(binary[2])*2
4 bit3 = int(binary[1])*4
5 bit4 = int(binary[0])*8
6
7 denary_out = bit1 + bit2 + bit3 + bit4
8 return denary_out
9
10
11 def main():
12 binary_in = input("Enter the binary string")
13 denary = binary_to_denary(binary_in)
14 print("The binary value", binary_in, "in denary \
is", denary)
15
16
17 if __name__ == '__main__':
18 main()
75
A program which converts a denary value between 0-15 to a 4-bit
binary value
1 denary = int(input("Enter the denary number between \
0 and 15"))
2
3 binary = ["0","0","0","0"]
4
5 if denary > 15:
6 print("error")
7 if denary >=8 and denary <=15:
8 binary[0] = "1"
9 denary = denary - 8
10 if denary >=4:
11 binary[1] = "1"
12 denary = denary - 4
13 if denary >=2:
14 binary[2] = "1"
15 denary = denary - 2
16 if denary >=1:
17 binary[3] = "1"
18
19 for count in range(len(binary)):
20 print(binary[count],end="")
76
Write a function which takes in 1 hexadecimal digit as an argument
and returns the denary equivalent.
77
Q1) What is the correct answer in Q1 below? Fill in the gap on the
if statement on line 24
1 def correct(score_in):
2 print("Well Done, this is the correct answer")
3 score_in = score_in + 1
4 return score_in
5
6 def quiz():
7 score = 0
8
9 print("""
10 Why do computers need primary storage?
11
12 A) To provide fast access memory to the CPU in the \
13 form of RAM and ROM
14 B) To provide long term storage of files on a hard \
15 disk drive
16 C) To act as RAM and allow programs to keep running \
17 when RAM is full
18 D) To provide storage in case secondary storage runs\
19 out
20 """)
21
22 Q1 = input("Choose a letter").upper()
23
24 if Q1 == "______":
25 score = correct(score)
26 print(score)
27
78
Examine the binary search program below.
79
Q1) What line is the function called on?
Q4) When the program is run and the target_in is 10, what is the
output?
Q5) When the program is run and the target_in is 20, what are the
mid values that are examined?
80
Examine the program below which is used to issue store discount
1 discounts = [["summer10",0.1],
2 ["welcome",0.15],
3 ["refer20",0.2]]
4
5 discount = 0
6
7 total = float(input("What is the order total: £"))
8 discount_in = input("Do you have a discount \
9 code?").lower()
10
11 if discount_in == "yes":
12 discountcode = input("Enter a discount code").lower()
13
14 valid = False
15
16
17
18
19
20 for count in range(len(discounts)):
21 if discountcode == discounts[count][0]:
22 discount = discounts[count][1]
23 valid = True
24
25 if valid == False:
26 print("Invalid discount code")
27
28 total = total - (total*discount)
29 print("Your total is £%.2f" %total)
30
81
Q1) Re-write the 2D list to include another discount code called
"loyalty25" worth 25% off.
82
A bubble sort iterates through an array (or list) of numbers from left
to right. If the number being checked is greater than the next item
in the array, the numbers are swapped. One way of achieving this is
by storing the first number in a temporary vaiable.
nums[j] nums[j+1]
9 1 12 3 4 8
Q1) After the program runs, what is the value of temp?
Q2) In the above scenario, what are the final values of nums[j] and
nums[j+1]? Explain whether the bubble sort has worked for the first
two items?
83
Q3) What is the name of the programming construct shown in the
program:
A. Sequence
B. Selection
C. Iteration
Q4) Give the name of two variables in the bubble sort snippet:
Q6) Explain why you might use a bubble sort instead of a different
sorting algorithm:
84
The size of a text file can be calculated by using the following
formula:
Q1) Write a subprogram which takes the bits per character and
number of characters as parameters and returns the file size in
Q2) ASCII is a character set which always uses 8 bits per character
If a text file encoded using ASCII has 1000 characters. How many
bits will the file size be?
Q3) Text is always stored as binary. ASCII has 8 bits and therefore
can represent 2^8 characters. Some formats of Unicode use 32
bits per character. This would create larger file sizes. Explain why
you might want to use Unicode instead of ASCII?
85
Q4) The file size returned will be given in bits, therefore we can
convert this to Kilobytes by dividing the answer by (8 * 1000.)
Use the space below to show how the function may be called. The
answer should be outputted in KB.
86
The size of a sound file can be calculated by using the following
formula:
87
The file size returned will be given in bits.
Use the space below to show how the function may be called. The
answer should be outputted twice, once in KB and again in MB.
88
Eirini Kolaiti came up with the great idea of putting example solutions to
the challenges at the back of the book. I will also post these solutions
online at: http://bit.do/LBOA2
There is always more than one way to solve a problem. Even if the
algorithm is well-defined, there may be alternative programming
approaches. The following pages present examples which you can
compare to your own answers. Comments have been provided to aid your
understanding, you should develop the habit of commenting all your
programs.
Do not worry if you have written an alternative solution. Also be aware
that these solutions were not produced by typing the whole program out
and running them with no syntax and logic errors on the first time! There
was a debugging process as I wrote each line or block of code.
Encountering errors whilst iteratively testing is the "normal" way to
develop programs.
def main():
print("""
1 Computer Science
2 Music
3 Dance
4 PE
""")
opt_num = int(input("Enter a number to choose an
option"))
subject = options(opt_num)
if subject == "Error":
print("You entered an invalid number")
print("Please enter a number between 1 and 4")
return main()
else:
print("You chose", subject)
main()
90
def mystery_number(num):
if num == 3:
print(1)
elif num < 5:
print(8)
else:
print(num)
# B, E, D, C, A
91
def initials_only(first, middle, last):
#slice only the first character from each string
initials = first[0]+middle[0]+last[0]
return initials
def subject_shortener(subject):
shortened = subject[0:3]
return shortened
subj_out=subject_shortener(subj)
return volume
92
def add(num1, num2):
out = num1 + num2
return out
1) C. na
2) B. o
3) D. 8
4) B. A value which can not change whilst the program is running
93
def is_odd(number_in):
if int(number_in) %2 == 0:
return("The number is even")
else:
return("The number is odd")
def main():
number = input("Enter a number")
if number != "STOP" :
odd = is_odd(number)
print(odd)
# call the main function again i.e. loop back to the
top
# and ask for another number
return main()
else:
exit()
94
Q1)
num1 num2 Output
1 8 0
3 9 1
14 10 2
21 19-28 4
Q2)
a) 21 DIV 7 = 3
b) 9 DIV 4 = 2
c) 8 DIV 3 = 2
print(acronym)
95
acronym = ""
words = input("Enter words to be turned into an
acronym")
import random
if dice1 == dice2:
print("Game loading")
else:
# Use input to enable the user to press enter to continue
# looping
again = input("Press enter to roll again")
96
import random
numbers = [9, 8, 72, 22, 21, 81, 2, 1, 11, 76, 32, 54]
highest = numbers[0]
numbers = [9, 8, 72, 22, 21, 81, 2, 1, 11, 76, 32, 54]
def highest_num(numbers_in):
highest = numbers[0]
return highest
highest_out = highest_num(numbers)
print("The highest number is", highest_out)
97
obvious = ["password", "qwerty", "hello123", "letmein", "123456"]
# Length check
if len(password) < 8:
print("Your password is too short. Please use at least \
8 characters")
if num == 0:
print("To make your password more secure, you could include \
numbers")
if upper == 0 or lower ==0:
print("To make your password more secure, you could include \
upper and lower case letters")
if char == 0:
print("To make your password more secure, you could include \
letters")
if num > 0 and char > 0 and upper > 0 and lower > 0:
print("Your password meets the minimum length requirements \
and contains a mixture of numbers, characters, upper and lower
case letters.")
98
import random
keeper_score = 0
player_score = 0
for count in range(5):
dive = random.choice(keeper)
if keeper == player:
print("Penalty saved")
keeper_score = keeper_score+1
else:
print("GOAAAAAAL!")
player_score = player_score+1
1) x y
0 2
1 2
2 4
3 4
99
Circle the correct answer based on the following code:
import random
for count in range(0,5):
num1=random.randint(1,10)
1) A. 10 and 1
2) B. 0 and 4
3) A. 5 times
def mean_of_list(numbers_list_in):
total = 0
for count in range(len(numbers_list_in)):
total = total + numbers_list_in[count]
def main():
numbers_list = [0,7,5,3,22,23,11,34,51,32,5,3,1]
mean = mean_of_list(numbers_list)
print("The mean average of", numbers_list, "=", mean)
main()
100
def vowel_counter(sentence):
A = 0
E = 0
I = 0
O = 0
U = 0
vowel_counter(sentence)
101
def marks(grade_in):
grades = [["A*","90"],["A","83"],["B","72"],
["C","60"],["D","49"],["E","30"]]
102
def vowel_counter(sentence):
vowel_list=[ ["A",0],
["E",0],
["I",0],
["O",0],
["U",0]]
vowel_counter(sentence)
103
def vowel_counter(sentence):
vowel_list=[ ["A",0],
["E",0],
["I",0],
["O",0],
["U",0]]
vowel_counter(sentence)
104
cs_scores = [["Karman","45","60","72"],
["Daniel","55","65","70"],
["Parker","71","78","78"],
["Jessica","68","79","80"],
["Edie","98","85","91"]]
total = 0
cs_scores=[["Theo","45","60","72"],["Angharad","55","65","70"],
["Sameer","71","78","78"],"Adrian","68","79","80"],
["Ayana","98","85","91"]]
total = 0
105
cs_scores=[["Theo","45","60","72"],["Angharad","55","65","70"],
["Sameer","71","78","78"],"Adrian","68","79","80"],
["Ayana","98","85","91"]]
def mean_student(scores_in):
total = 0
mean_student(cs_scores)
1)
x y output
0 0 Charlie
0 1 Dog
0 2 8
1 0 Dolly
1 1 Sheep
2) 2D-List
3) C. Iteration
106
1) B 2,3,4,5,3,4,5,6,3,4,5,6
2) C Wanda
3) D Index error: list index out of range
1101110
107
def new_user(username_in, password_in):
# define a function called new_user with two parameters:
# username and password
108
1) B
file = open("txtfile.txt", "a")
file.write("some text")
C file.close()
G found = False
if email == users[count][0]:
F found = True
return Found
E return Found
Correct order:
B A C G D F E
109
def hex_to_denary(hex_in):
# only convert values A to F
hex_A_to_F = [["A","10"],["B","11"],["C","12"],["D","13"],
["E","14"],["F","15"]]
convert = False
for count in range(len(hex_A_to_F)):
if hex_in == hex_A_to_F[count][0]:
convert = True
return int(hex_A_to_F[count][1])
def main():
main()
1) A
110
1) 30
2) List or Array
3) 2
4) Element is present at index 3
5) Element is not present in array
6) Integer division or floor division. A division where you ignore the
remainder and round down.
7) integer
1)
discounts = [["summer10",0.1],
["welcome",0.15],
["refer20",0.2],
["loyalty25",0.25]]
2) Boolean
3)
file = open("codes.txt","r")
discounts = eval(file.read())
file.close()
4)
Subprograms such as procedures and functions can be called
anywhere in the program.
Subprograms reduce the number of lines of code i.e. creates
shorter programs.
The programs are also more manageable as errors or
changes to one subprogram means you only make the
change or the correction in one place, not several places
throughout the program.
111
4 continued)
Multiple people can work on the program, each working ona
different subprogram.
The subprograms can be tested in isolation.
Subprograms can be re-used in other programs and also
imported .
112
1) Based on the snippet shown, nums[j] is 9 and this is stored in
temp
2) nums[j] and nums[j+1] both equal 1. The bubble sort has not
worked. Line 18 should be nums[j+1] = temp. This ensures the
original value of nums[j] i.e. 9 is stored in temp and then copied to
nums[j]. The code as it stands first replaces nums[j] with 1 then
replaces the value of nums[j+1] with the updated value of nums[j].
3) Selection
113
1)
def text_size(bits_char, num_char):
size = bits_char * num_char
return size
4)
def main():
5) 1KB
114
def file_size(frequency, bits, duration):
size = frequency * bits * duration
return size
def main():
115
Coding Club Python Basics Level 1 (2012) ¹ Chris Roffey
Coding Club Next Steps Level 2 (2013)
Python by Example1 Nichola Lacey
Making Games with Python and Pygame (2012) Al Sweigart
Automate The Boring Stuff With Python (2015)
www.inventwithpython.com
www.pythonprogramming.net Sentdex
See also: Youtube channel- sentdex
www.kidscancode.org Chris and Priya
See also: Youtube channel- KidsCanCode Bradfield
Youtube channel– MrLauLearning William Lau
Youtube channel– Tech With Tim Tech With Tim
Youtube channel- Corey Schafer Corey Schafer
Youtube channel– Computerphile Computerphile
How We Learn (2014) Benedict Carey
Why We Sleep (2017) Matthew Walker
¹ Brilliant books for absolute beginners. These "how-to" guides take you step by step
through the basic programming structures required to access most of the material in this
book.
116
117
My knowledge and understanding of programming was initially developed
by attending courses run by Ilia Avroutine, Darren Travi, Graham
Bradshaw, David Batty and Sarah Shakibi. I have also benefitted greatly
from the mentoring of Merijn Broeren, Elizabeth Hidson and Andy Swann.
The generosity of those who produce resources to teach programming
such as Chris Roffey, Al Sweigart and Sentdex along with the wider CAS
and Facebook community is also a great source of inspiration. To all of
the aforementioned, I am indebted. You have given me the confidence to
keep developing my programming skills independently and to eventually
share these skills with you on CAS, Facebook, Youtube and in my books.
To further my understanding of programming, I have had the great
privilege of sharing thoughts with Peter Kemp, Alex Parry, Eirini Kolaiti,
Richard Pawson, Scott Portnoff, Sue Sentence, Meg Ray and Alan
Harrison. All of the brilliant teachers and programmers read drafts of this
book and their comments have improved the book significantly.
I hope that my compromise of including procedures as well as non-
modular programs is forgiven. I have to be realistic and acknowledge that
for all novices, writing programs without subroutines is a starting point
and an achievement in itself. There are many solutions to a given
algorithm and provided that the output is correct and the algorithm is
reasonably efficient, we should recognise these as correct (up to GCSE
level) even if subroutines are not used.
I thank my colleagues, particularly Lloyd Stevens, Leila Lassami, Jaime
Vega, Gavin Tong, Sahima Patel, John Seery, Agata Obirek and Jamie
Brownhill at Central Foundation Boys’ School (CFBS). They have
supported me with their time, patience and agreeable responses to my
(occasionally unreasonable) demands! I also thank the students at CFBS
whose hard work have provided me with further motivation to improve
my teaching . Our students always inspire us to be better .
To Suki, Zi and Q, this book would not be possible without you. Many
people ask me how I have time to write these books and my answer is, "I
have an understanding family!" Thank you for your continued support.
118
119
120
121
122
Have you ever wanted to become more fluent in Python programming?
Perhaps you find the prospect of file writing or using 2D data structures
daunting? If so, then this is the book for you!
This range of exercises will help you to become more fluent in Python and
ensure that you are comfortable with any question format in a
programming exam.
After finishing this book, you should feel more familiar with:
While loops and For loops
Concatenating different data types
Using procedures and functions
Working with 1D and 2D lists and arrays
File reading and writing
This book will show you how to write better Python programs and will
expose you to the key skills that are required to do well in any secondary
school programming assignment or exam.