How To Code in Python GCSE, IGCSE and National
How To Code in Python GCSE, IGCSE and National
How To Code in Python GCSE, IGCSE and National
Find out more and sign up for a free trial – visit: www.hoddereducation.co.uk/dynamiclearning
How to code in
Python
GCSE, iGCSE, National 4/5 and Higher
Greg Reid
Every effort has been made to trace all copyright holders, but if any have been inadvertently overlooked, the Publishers will
be pleased to make the necessary arrangements at the first opportunity.
Although every effort has been made to ensure that website addresses are correct at time of going to press, Hodder
Education
find cannot be held responsible for the content of any website mentioned in this book. It is sometimes possible to
a relocated web page by typing in the address of the home page for a website in the URL window of your browser.
Hachette UK's policy is to use papers that are natural, renewable and recyclable products and made from wood grown in
well-managed forests and other controlled sources. The logging and manufacturing processes are expected to conform to
the environmental regulations of the country of origin.
Orders: please contact Bookpoint Ltd, 130 Park Drive, Milton Park, Abingdon, Oxon OX14 4SE.
Telephone:
to +44 (0)1235 827827. Fax: +44 (0)1235 400401. Email education@bookpoint.co.uk. Lines are open from 9 a.m.
5 p.m., Monday to Saturday, with a 24-hour message answering service. Visit our website: www.hoddereducation.co.uk
ISBN: 978 1 5104 6182 6
© Greg Reid 2020
First published in 2020 by
Hodder Education
An Hachette UK Company,
Carmelite House, 50 Victoria Embankment
London EC4Y 0LS
Impression number 5 4 3 2 1
Year 2024 2023 2022 2021 2020
All rights reserved. Apart from any use permitted under UK copyright law, no part of this publication may be reproduced or
transmitted in any form or by any means, electronic or mechanical, including photocopying and recording, or held within
any information storage and retrieval system, without permission in writing from the publisher or under licence from the
Copyright Licensing Agency Limited. Further details of such licences (for reprographic reproduction) may be obtained from
the Copyright Licensing Agency Limited, www.cla.co.uk
Cover photo © AndSus/stock.Adobe.com
Illustrations by Aptara Inc.
Typeset in India by Aptara Inc.
Printed in Spain.
A catalogue record for this title is available from the British Library.
Contents
Chapter 1 – Introduction 1
5
Contents
Chapter 1 – Introduction
What makes a good programmer?
Good programmers are logical thinkers. They have the ability to take a problem, break
it down into its component parts and design a solution. They can then implement their
solution as a sequence of instructions written in a programming language. If all this
sounds like a high-level skill, well it is. Programmers are in high demand all over the
world and often earn good salaries.
Although few people have this natural talent, EVERYBODY can learn to be a better
progr ammer.
The three stages of programming
All programmers work through three stages when coding a solution to a problem.
1 The programmer must understand the problem. For simple problems, understanding
may be almost instantaneous. More complex problems may require time, research and
questioning in order to fully understand what is required.
2 The problem is broken down into smaller and smaller sub-problems in a process
called decomposition. Depending on the complexity and size of the problem,
decomposition may involve creating a formal design or it may simply take place inside
the programmer's head. The purpose of decomposition is to identify the individual
components (or building blocks) of the problem and programming structures that will
be required to build the solution.
3 Each component is coded, tested and combined with others until a completed program
solution is achieved.
Read File
Decision
Calculation
Key Input
Repetition
3.
Calculation
Decision
Store Data
Display
If an earlier program has not been saved, you may use one of the downloaded solutions as
your starting point (see below).
Variables
The second line of the code in Example 3 above creates a variable (or storage location)
called "userName". When the user types the name (enters text) and then presses enter,
the keyboard input "Greg" is stored in the variable.
You might want to imagine variables as boxes that your program Gr
temporarily stores data in while it's running. eg
A variable can be given almost any name made up of letters and
user
numbers. Some exceptions to this are: Nam
e
■
You cannot use two or more separate words as a variable name.
Note that this book uses camel case (using capital letters in the
middle of a word) in place of two words. For example, "userName" instead
of "user name".
■
In Python, variable names should always start with a lower case letter. This is because
capital letters are reserved for something else.
■
A variable cannot be called any of the statement words of the Python language.
For example, "print" or "input" would not be valid variable names.
An input( ) statement can be contained with str( ), int( ) or float( ) statements to ensure
that the correct type of data will be entered by your user. If the user enters the wrong
type of data the program may display an error message and crash.
Example 6 – Concatenation
In programming, concatenation means to join two strings together.
Program Code
The second print( ) statement uses the + symbol to concatenate the two variables
"firstName" and "surname". Note the difference between the outputs produced by the
two print lines. When strings are concatenated, they are literally joined together and
displayed without a space.
1 Output
productName = "Bicycle
Chain"
print(productName)
2 Output
dogBreed =
"Labradoodle"
3 Output
dogAge = "Two"
print(dogBreed,
dogAge)
4 Output
name = "Scott"
age = 23
5 State the output "aged",
print(name, if the user enters "video".
game = input("Please enter a word")
age) Output
print(game, game + game)
coffee = "Lava Java"
6 var1 = "Going" Output
print(coffee + coffee)
var2 = "Gone"
print(var1, "Going" + var2)
7 print("This,"+" is a plus +","symbol")
Output
Love the life you live. Live the life you love.
print(23 + 45) 68
If a calculation is placed directly inside a print( ) statement, the result of the calculation
is displayed.
Program code
num1 = 5 Output
num1 = 7+2 9
print(num1)
The output is 9 because the original value 5, stored in the variable num1, is replaced by the
result of 7 + 2 in the second line of code.
This is an important concept in programming as many programs involve constantly storing,
updating and outputting text or numbers. This also highlights a potential problem when
writing programs: errors can be created by accidentally replacing text and numbers you
wish to keep.
Puzzle set 2 – Simple calculations
For each of the following puzzles, think through the code and write down the exact output
produced. Pay attention to:
■ whether the answer should be written as an integer or float number
■ when the numbers stored in variables are updated.
As before, the puzzles will get harder.
11 print(12/6)Output
13 p r i n t(4*4) Output
14 print(int(6/2) + 3) Output
15 p r i n t((7+3)/2) Output
16 print((12+6+2)/(3+2)) Output
17numberOne = 6Output
numberTwo = 13
print(numberOne + numberTwo)
18
numberOne = 5Output
numberTwo = 16
numberThree = numberOne * numberTwo
print(numberThree)
19Output
numberOne = 5
numberTwo = numberOne * 2
numberThree = numberOne + numberTwo + numberTwo
print(numberOne,numberTwo,numberThree)
20numberOne = 20 / 4Output
numberTwo = numberOne + 55
numberThree = numberTwo / 6
print(numberOne,numberTwo,numberThree)
word = es
"testing"
word2 =
word[1:3]
The numbers in the square brackets refer to a point between each character in the
print(word2)
string. These can be positive numbers (counting each point from left to right) or negative
numbers (counting from right to left) as shown in the example below.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
M o s t E x c e l l e n t
If either value is missed out the substring defaults to the first or last character.
Program Code 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
the
quotation = "The answer is Forty Two" answer is
smallQuotation = quotation.lower() forty two THE
print(smallQuotation) ANSWER IS FORTY
print(quotation.upper()) TWO
Output
The above code replaces the text "Hard" with the text "Well". The rest of the string
remains unchanged.
A f l e e t i n g b e a t i n g o f h e a r t s
−28 −27 −26 −25 −24 −23 −22 −21 −20 −19 −18 −17 −16 −15 −14 −13 −12 −11 −10 −9 −8 −7 −6 −5 −4 −3 −2 −1
hearts" print(lyric[0:6])
word2 = "processing"
word3 = "unit"
word4 = word1[0:1].upper()
word5 = word2[0:1].upper()
word6 = word3[0:1].upper()
print(word4 + " = " + word1)
print(word5 + " = " + word2)
print(word6 + " = " + word3)
34 Output
password = "beetle man"
passwordLength = len(password)
print(passwordLength)
Output
35password = "Sphinx"
passwordLength = len(password)
print("Your password", password, "is", passwordLength, "characters long"
36quotation = "There are only two kinds Output
of people who are really fascinating:
people who know absolutely everything,
and people who know absolutely nothing. - Oscar Wilde"
print(quotation.count("re"))
37quotation = "Whatever you are, be a bad one. Abraham Lincoln"
quotationNew = quotation.replace ("bad","good")
print(quotationNew)Output
42 The following program uses string handling to create and display a simple password.
Work out what the password is.
number = 4.7
round(4.6783,1)
print(number)
The correct computing term for these values is parameters. We say that parameters
are passed into the function. The function then returns the result: in this case a rounded
number.
number = 4.6783 4
print(int(number))
import math 5
number =
math.ceil(4.2045)
print(number)
The first word of this function, "math", is a module library (collection) of extra
mathematical functions that can be added to Python to extend the capabilities of the
programming language.
This function requires "import math" at the top of your program. This line adds lots of
additional maths functions to the standard capabilities of Python.
leftOver = 3
13%5
print(leftO
Here
ver)the program shows that 13 divided by 5 is 2 remainder 3.
p r i n t(p o w(4,2)) 16
44 shoeSize = 10.3Output
print(round(shoeSize,0))
45 import math
Output
weight = 78.65
print(math.ceil(weight))
46 offcut = 25%7Output
print(offcut)
47 import math
Output
value = 12.5%3
print(math.ceil(value))
48
import mathOutput
roomLength = 20
plank = 3
woodNeeded = math.ceil(roomLength/plank)
print("The number of whole planks needed =",woodNeeded)
49
import mathOutput
value = 57.884
decimal = value – int(value)
print(round(decimal,2))
50 cat = 5.91Output
dog = int(cat)
p r i n t(p o w(d o g,2))
51 import mathOutput
num1 = 12.7
num2 = 30.3
num3 = (int(num2) - math.ceil(num1))
num4 = pow(3,(num3%5))
p r i n t(n u m 4*(i n t(n u m 2/10)))
K KY8 9HL
Y
8
9
H
Program
L 5 – Calculate the area of a rectangle
Ask your user to enter the length and width of a rectangle. Your program should calculate
the area of the rectangle (length × width) and display the result with a suitable message.
Input Output
2 26
6
The following challenges all use substring and the string functions (lower, upper, len, count
and replace) explained in Examples 11–15 and covered by Puzzles 24–42.
K KY8 9HL
Y
8
9
h
Program
l 8 – Name length
Write a program that asks the user to enter their forename and surname. The program
should output the total numbers of letters in their name.
Input Output
Output
Input Output
Input Output
Please enter the volume of the 1279 sweets fit into the jar.
jar (cm3): 2712.96
Please enter the volume of one
sweet (cm3): 2.12
Often the complexity of a program is increased by the complexity of the problem scenario.
A good programmer must be able to examine and understand scenarios they may have
never encountered previously. The last few program challenges have more complex
scenarios. Read each one carefully to understand what is required.
Output
Input
Output
Input
is found to be true then the program will execute one Add £4.00 postage
or more lines of code. to totalSales
Blocks of code
Selection statements are written as blocks of code. Fig 11.1: Flowchart showing simple
Programming languages use a variety of ways to show program design
whether code is part of statement. Python uses:
■
a colon (:)
■
followed by indented code.
To indent code means to move it to the right compared to the line above, as shown with the
twoticket
print statements
= below.
str(input("Enter another ticket:
child/adult/concession")) if ticket == "child":
print("Remember there are height restrictions on
some rides")
print("Please read all signs carefully before
queuing")
Theticket
block of=code ends when the nextanother
str(input("Enter line of the ticket:
program isn't indented. Thus the final line
above is not part of the selection statement.
child/adult/concession"))
Beware! Incorrect indentation can cause errors in your code. If the second print statement
were not indented, it would be outside the selection block. If it were outside, this would
change how it displays its message – it would always display its message and not just
when ticket == "child".
Program Code
A not() operator reverses the condition so rather than checking if the score entered is
76 or 58, the addition of the not means that the condition is only true if the score is not
equal to 76 or 58.
This example can be used to highlight another fact about programming: often there are
several ways to achieve the same outcome. By changing the highlighted code below,
the program below will produce exactly the same results as example 26.
score = int(input("Please enter
your score.")) if score == 76 or
score == 58:
print("Well done, target score
achieved.") else:
print("You did not hit the target
scores.")
Example 27 – Building more complex "if" statements
The complexity of the "if" statements you build is only limited by your own ability to
work out the logic of the conditions. A more complex example is shown below:
Program Code
Example puzzle
number = int(input("Please enter an integer"))
if number < 10:
print("Low")
if number >= 10 and number <= Remember:
20: indented lines are only
executed if the conditions are true.
print("Middle")
if number > 20:
print("High")
e User input
Output
50
temp = int(input("Please enter a temperature"))
53 if temp >= -273 and temp <= 42:
print("Solid")
elif temp >43 and temp < 87:
print("Liquid")
else:
print("Gas")
a User input
60 Output
b User input
-50
Output
c User input
43
d User input Output
2999
Output
e Which of the above inputs (a, b, c or d) highlights an error in the logic of the
program? Describe how you would correct the error in program.
d State an input that would output "Valid age", "School age" and "Working age".
value = float(input("Please enter the value of your item"))
55 weight = float(input("Please enter the weight of your item in kilograms"
if value <= 0:
print("Invalid value")
postage = 0.0
if weight >= 0 and weight < 2:
if value > 0 and value < 50:
postage = 1.5
if value >= 50 and value < 150:
postage = 2.75
if value >= 150:
postage = 5.5
elif weight >= 2 and weight < 10:
if value > 0 and value < 50:
postage = 2.5
if value >= 50 and value < 150:
postage = 4.4
if value >= 150:
postage = 8.35
elif weight >= 10 and weight < 25:
if value > 0 and value < 50:
postage = 7.55
if value >= 50 and value < 150:
postage = 12.3
if value >= 150:
postage = 15.0
else:
postage = 25.0
print(postage)
value
62
weight
b User
1.5input Value of postage displayed
value 0
weight 2.2
value
172
weight
d User
19 input Value of postage displayed
value
250
weight
e User
32.5 input Value of postage displayed
value
34
weight
f User
2.5input Value of postage displayed
value
50
weight
56 The following
10 program uses some of the string functions learned in Section 1.
Beware, this is a difficult puzzle!
word = str(input("Please enter a
word"))
number = int(input("Please enter
an number")) if len(word[number:])
>= 3:
word = word + word
else:
word = word[0:2] + word[0:2]
if word.count("e") >= 3:
word = word.replace("e","a")
else:
word = word.replace("e","c")
print(word) Value of "word" displayed
Would you like some Always know where your towel is.
advice? Y
Program 21 – Go winner
Go is a 4000-year-old board game played by two players using
black and white stones. At the end of the game each player
counts their score then white adds on an extra 6.5 points to make
up for the fact they play second at the beginning of the game. The
player with the highest score is the winner.
Write a program that asks black and white to enter their scores,
adds on 6.5 points and displays the winner.
Input Output
three amounts and store the total. If the total is greater or equal to 1000 the total should
be doubled. Finally, the total should be displayed.
Input Output
Write a program to analyse the results of a braking test. The user should be asked to enter
one of two speeds (30 or 50) and the distance it took the car to stop in the test. To allow for
any measurement errors, the distance entered should be rounded up to the nearest whole
number. Finally the user should be given a message stating if their car has:
■
failed the tyre test – the car took longer than the recommended distance for the given
speed to stop
■
passed the test – the cars stopping distance was equal to or less than the recommended
Input Output
distance for the given speed.
Please enter the test speed (mph). Your car failed the
50 braking distance
Please enter the tested stopping test.
distance (m). 39.7
(ForPlease enter
example, £2054the first
raised amount
will result A total
in 2 * £2000 + £54 of £2454
= £4054 was raised.
total)
raised. 740 With the company bonus, this is £4454.
Open and rewrite Program 22 to account for the above decisions.
Please enter the second
amount raised. 690
Please enter the third amount
raised. 1024
Get next
measurement
from user
Add new
measurement
to total
Get next
Set counter to 0 measurement
from user
Get next
measurement
from user
Add new
Get measurement
measurement
from user
to total
Add new Add 1 to counter
measurement
to total
Ask user if they
Add measurement
wish to enter another
to total
measurement
Get next
measurement
from user
No Yes
Is counter > Is choice = Y?
Add new 999?
measurement
to total
× 1000 Yes No
Figure 14.1: Adding Figure 14.2: Adding measurements Figure 14.3: Adding
measurements using repetition measurements where user
without repetition input ends repetition
for money in 0
range(5): 1
print(money) 2
3
4
for oranges in 1
range(1,21,4): 5
print(oranges) 9
1
3
1
A negative step would count down rather than up. In this case, the first number must be
7
larger than the second.
for apples in 3
range(30,1,-6): 0
print(apples) 2
4
1
8
1
2
6
(not 17 because that would lead to 16 also being displayed in the output).
Possible answers are therefore: range(0,4,13), range(0,4,14), range(0,4,15) or
range(0,4,16).
Using the same program used in the above example, write down the simplest range( ) that
would produce the output shown.
Remember that a range( ) command can take three forms:
●
r ange(5)
●
r ange(2,7)
●
0
range(1,20,4)
1
64 Range Output from program 2
3
4
5
67 Range Output
1 from program
4
7
10
68 Range 45
Output from program
36
27
18
9
Program code
num1 = 5 Explanation
num2 = 7 Each time the code repeats, num1 stores the
current value of num1 + num2.
for loop in range(4):
num1 = num1 + num2 The value of num2 is then increased by 2.
num2 = num2 + 2 This process is repeated four times "range(4)".
print(num1, num2) The two variables are displayed.
The trace table is used to note the values stored by the two variables after each repetition
of the loop. This helps the programmer to identify mistakes in the logic of the code.
69num1
Output= 3
num2 = 2
for loop in
range(3):
num1 = num1 +
num2 num2 = num2
+ 3
70 print(num1, Output
num2)
num1 = 80
num2 = 40
for loop in
range(2):
num1 = num1 -
num2
num2 = num2 / 2
print(num1,
num2)
71num1 = 2 Output
num2 = 4
num3 = 6
for loop in range(4):
num1 = (num1 + num2 - 8)
* 2 num2 = num2 + num3
print(num1, num2, num3)
72num1 = 1 Output
num2 = 3
num3 = 5
for loop in range(5):
num3 = num1 + 3
num2 = num3 - 2
num1 = num3 + num2
print(num1, num2, num3)
num1 = 5
73 Output
num2 = 5
num3 = 5
for loop in range(200):
num3 = num1 - (num2 + 2)
num2 = (num2 - 2) - num3
num3 = num3 + 7
print(num1, num2, num3)
The loop variable will be used in the next few puzzles. Remember for range (3) the
variable would store 0 then 1 then 2. For range(3,7) the variable would store: 3,4,5,6.
For range(1,10,2) the variable would store 1,3,5,7,9.
74num1
Output= 2
num2 = 4
for loop in range(4):
num1 = num2 + num1
num2 = num1 - loop
print(num1, num2)
75num1 = 4 Output
num2 = 6
num3 = 0
for loop in range(3,7):
num1 = (num1/2 + num2/3) * loop
num3 = num2 + num1
print(int(num1), num2, int(num3))
76 start = 1 Output
for loop in
range(1,6):
start = start *
10
mid = start%loop
end = mid + loop
start = end
77 Remember
print(start,about concatenation
mid, of strings using the + symbol. For example,
end)
"bob"+"cat" = "bobcat".
Follow the concatenation taking place in this puzzle and write down the string
displayed in the final line.
text1 = "a" Output
text2 = "b"
text3 = ""
for loop in range(4):
phrase1 = str(loop)+
text1
phrase2 = text2 +
str(loop) if loop <=
2:
text3 = text3 +
phrase1
else:
78 Nowtext3
for a really=difficult
text3 + combines a lot of what you have learned up to this
one, which
phrase2 print(text3)
point. Well done if you get this puzzle correct.
text1 = "this" Output
text2 = "is"
text3 = "hard"
words = ""
number = 0
for diamond in range(len(text2),len(text3)):
words = words + text1 + text2
number = number + words.count("s")
words = words[2:5] + text3
number = diamond + number + text3.count("h")
print(number)
80guess = 0 Answer
while not(guess == 34):
guess = int(input("Please enter a
number")) print("program finished")
Input required to exit loo
p ABCD 20 22 24 34
81num = 34 Answer
while num == 34 or num == 22 or
num == 20:
num = int(input("Please enter a
number")) print("program
Input required to exit loo
finished")
p ABCD 20 22 24 34
82temperature= 0 Answer
while temperature<= 45:
temperature= int(input("Please enter a
temperature")) print("program finished")
Input required to exit loo
p ABCD −3 45 76 34
83number = 0 Answer
while number < 5 or number > 17:
number = int(input("Please enter a
number")) print("program finished")
Input required to exit loo
p ABCD 17 45 −5 4
84length = 0 Answer
while not(length >= 22 and length
<=45):
length = int(input("Please enter a
length")) print("program finished")
Input required to exit loo
p ABCD 14 0 52 27
87text = ""
while text.count("a") <=1 or Answer
len(text) < 4:
text = str(input("Please enter a
word")) print("program
Input required to exit loop
finished")
ABCD
afar blast aga ta
As always, these new challenges may also require you to use skills and knowledge from
previous sections. The challenges start off nice and easy but will get progressively harder.
Input Output
Input Output
Input Output
Input Output
Mon 12°C Tue 14°C Wed 7°C Thur 6°C Fri 7°C Sat 11°C Sun 11°C
A program needs to be created to allow the user to enter the seven temperatures.
The average for the week should be displayed, to two decimal places, as shown below.
Input Output
Input Output
Input Output
Odd Numbers
List 1
3
5
7
9
11
Input Output
Input Output
Enter your menu choice (Q, Enter your menu choice (Q,
A, K or L) a A, K or L) V
A selected V is not valid. Enter Q, A,
K or L
L
L selected
Output
1D List
Where multiple values need to be stored (say, 1000 temperature readings taken from a
sensor), we need a larger data structure called an array. An array holds data in indexed
elements. The program uses the array name and index to determine where data should be
stored or where it should be fetched from.
index name
0 Omar
1 Jill
2 Derek
3 Ploy
4 Brad
5 Jessi
e
For example, print(name[3]) would display "Ploy".
Note that while Python can create arrays (you can download and install a module library
called NumPy), for the purposes of learning how to use arrays we will use Python's list
structure. While these are not truly arrays, for beginners, lists behave in a similar way. You
may wish to research the difference between lists and arrays when you have completed
this book.
As shown above, a list can be visualised as a column of indexed (numbered) boxes.
When initialising (creating) a list in a program, the programmer must enter:
■
the name of the list
■
the size of the list (number of elements/boxes)
The command for declaring an empty list in Python looks like this:
For a list of 6 numbers: For a list of 10 strings:
teamScores = [0]*6 teamNames = [""]*10
2D list
Programmers sometimes use lists structures with more than one dimension. These are
useful when the data being stored takes the form of a table or rectangular grid. A 2D list
has two indexes which work like coordinates to identify a single element in the list.
first index 0 1 2
0 Andy Warhol Pop Art
1 Pablo Picasso Cubism
2 Leonardo da Vinci Renaissance
Artists
0 1 2
0 Andy Warhol Pop Art
A new sublist is created for each artist until the final structure looks like this:
Artists
0 1 2
0 Andy Warhol Pop Art
0 1 2
1 Pablo Picasso Cubism
0 1 2
2 Leonardo da Vinci Renaissance
A single element of the list of lists structure is accessed using the index of the main list
and the index of the sublist.
print(artists[1][2])
This print statement would display Cubism.
names =
["Azil","Gillian","Brian","Kuba","Jean","Doreen","Kye","Pa
t","Dennis","Ann"] ages = [13,14,13,15,16,13,14,14,14,13]
p r i n t(n a m e Azil 13
s[0],a g e s[0]) Gillian 14
p r i n t(n a m e Brian 13
s[1],a g e s[1]) Kuba 15
p r i n t(n a m e Jean 16
s[2],a g e s[2]) Doreen 13
p r i n t(n a m e Kye 14
s[3],a g e s[3]) Pat 14
p r i n t(n a m e Dennis 14
s[4],a g e s[4]) Ann 13
p r i n t(n a m e
s[5],a g e s[5])
p r i n t(n a m e
66 How to Code in Python
s[6],a g e s[6])
p r i n t(n a m e
Chapter 17 – Examples of lists
Although the previous code works, it is a poor solution. If our lists held 1000 names and
ages we would need to write 1000 print commands.
As the print command is being repeated, a simpler solution would be to use a loop.
Program Code
names =
["Azil","Gillian","Brian","Kuba","Jean","Doreen","Kye","Pa
t","Dennis","Ann"] ages = [13,14,13,15,16,13,14,14,14,13]
for counter in range(10):
print( names[counter], ages[counter] )
The program now has only one print( ) statement. The loop variable 'counter' is used to
change the index of the list element being displayed. Counter will increment by one each
time the loop repeats. This will produce the same output as before.
Note that by using the len( ) function we don't even need to know how many elements
are in our list. The following code would work for any length of list.
Program Code
names =
["Azil","Gillian","Brian","Kuba","Jean","Doreen","Kye","Pa
t","Dennis","Ann"] ages = [13,14,13,15,16,13,14,14,14,13]
for counter in range(len(names)):
print( names[counter], ages[counter] )
names = [""]*5
ages = [0]*5
for counter in range(5):
names[counter] = str(input("Please enter name " + str(counter+1)))
ages[counter] = int(input("Please enter " + names[counter] + "'s age"))
The program uses the counter variable to ensure that each time a name and age are
entered by the user they are stored in different elements of the list.
16 loop, counter = 4
Note that the second input line uses the name that was just entered by the user. This
provides a clearer message for the user. It is always good practice to make your
program as easy to use as possible.
Conditional loop
Used when we don't know how many values will be entered.
Program Code
names = [""]*0
ages = [0]*0
counter = 0
morePeople = "Y"
while morePeople.lower() == "y":
names.append(str(input("Please enter name " +
str(counter+1))))
ages.append(int(input("Please enter " +
names[counter] + "'s age"))) morePeople =
str(input("Do you wish to enter more? Y/N"))
if morePeople.lower() != "y":
print("Entry complete")
else:
A conditional
counter =loop allows data
counter + 1to be input until the user decides to stop. It requires the
following additions:
■
We start by initialising the lists with no elements because we don't know the size of
the final lists. The append( ) function is used to add a new element to the list making
it grow in size with each new input.
■
We need a way of controlling whether or not the while loop will repeat or finish. We
can use another variable (morePeople) and an input ("Do you wish to enter more?
Y/N") to do this.
The above code uses a variation of a fixed loop to create a single sublist and then repeat
this multiple times.
Looking at the example below:
■
The first number (5) is the value being stored in every element of the 2D list.
■
The second number in the code (4) creates the number of elements in the sub list.
■
The last number in the range( ) equals the number of main list elements.
gridPoints = [[5] * 4 for main in range(2)]
gridPoints second index
This would create:
first index 0 12 3
0 5 5 5 5
1 5 5 5 5
When the nested loop first executes, the two loop variables store day = 0 and hour = 0.
While day remains at 0, the inner loop will count from hour = 0 up to hour = 23. When the
inner loop finishes the outer loop will repeat and day will increment (day = 1). The inner
loop then repeats another 24 times (0 to 23). This process repeats until all 168 (7 outer
loops and 24 inner loops) list elements store a temperature.
The 2D list will be filled with temperatures one row at a time.
Second index (hour)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Temperatures
0 1.2 12.0 7.2
1
2
First index (day)
This example displays the data in example 42 in rows and columns. The end= ' '
statement forces the next print statement to continue to output on the same line (when
normally print statements output onto a new line). For the inner loop (hour), this means
that each of the temperatures will be displayed next to each other. A space character ""
is added to the output to separate the values.
The purpose of the empty print( ) statement is to cancel the effect of the 'end' statement
each time the outer loop (day) increments.
Using this simple technique, the output can be displayed on 7 lines, each with 24
temperatures. Without the additional code all 168 temperatures would display vertically
with each on its own line.
89 numbers = numbers
[9]*5
numbers[0] 0
= 5
1
numbers[2]
= 9 2
numbers[4]
= 0 3
90 numbers = [0,1,2,3,4]
numbers
numbers[1] = 4
numbers[4] = 1 0
numbers[3] = 2
1
92 numbers = [12,2,24,4,36]
numbers
numbers[2] = 3
numbers[4] = numbers[2] 0
numbers[2] = 6
1
numbers[1] = 20 + numbers[3] - numbers[2]
2
93 import math
numbers = [5]*5 numbers
numbers[3] = math.ceil(numbers[1]*3/2)
0 - 3
numbers[0] = pow(numbers[3],2) - 16
numbers[4] = int(numbers[0] / 4) 1
94numbers = [10]*5
numbers
numbers[2] = numbers[1] + 15
numbers[3] = numbers[0] - 5 0
if numbers[2] + numbers[4] >= 35:
numbers[0] = numbers[0] + 10 1
else: 2
numbers[0] = numbers[0] - 10
if numbers[0]%2 == 1: 3
numbers[4] = numbers[3] + 2
4
else:
numbers[4] = numbers[0] + 10
95numbers = [0]*5
numbers
for nums in range(5):
numbers[nums] = 3 0
96 numbers = [0]*5
numbers
counter = 0
for loop in 0
range(5):
1
numbers[loop] =
counter counter = 2
counter + 1
3
97 numbers = [0]*5
numbers
for loop in range(5):
numbers[loop] = loop 0
98 numbers = [2]*5
numbers
for loop in range(4):
numbers[loop +1] = numbers[loop] + loop + 1 0
99 wordLength = [0]*5
wordLength
words = ["silly","humorous","funny","side-
splitting","amusing"] for loop in range(5): 0
wordLength[loop] = len(words[loop])
1
2 2
3 3
4 4
101 townList1 =
["Dover","Maidstone","Ayr","Shepway","Pembro
ke"] townList2 = [""]*5 townList1 townList2
for loop in range(5):
0 0
townList2[loop] = townList1[loop].lower()
1 1
2 2
3 3
4 4
102 places =
["Glasgow","Swansea","Lisburn","Thurso","B
olton"] letterCount = [0]*5 places letterCount
for loop in range(5):
0 0
letterCount[loop] =
places[loop].count("o") 1 1
2 2
3 3
4 4
103 What is stored in the "elements" list after the program has been executed?
elements =
["Copper","Titanium","Iron","Lead","Silic elements
on"] for loop in range(5): 0
if elements[loop].count("i") > 1:
elements[loop] = elements[4-loop] 1
104 This contains part of a well-known algorithm. Work out what numbers
is stored in the numbers list after the loop has finished executing.
0
numbers = [45,9,35,92,67]
temporary = 0 1
for loop in range(4):
if numbers[loop] > 2
numbers[loop+1]: temporary = 3
numbers[loop]
numbers[loop] = 4
numbers[loop+1]
105 This puzzle uses substring
numbers[loop+1] (nameList1[loop][0:1]) to extract part of the stored strings
= temporary
for a list. If you can't remember how sub strings work, you can look back at Section 1.
What strings will be stored in the two lists once the program has been executed?
nameList1 = ["Bob","Derek","Fred","Usman","Abubakar"]
nameList2 = ["Mary","Nida","Jill","Tracy","Helen"]
temporary = ""
for names in range(5):
if nameList1[names][0:1] < nameList2[names][0:1]:
temporary = nameList1[names ]
nameList1 nameList2
nameList1[names] = nameList2[names]
nameList2[names] = temporary 0 0
1 1
2 2
3 3
4 4
106 What values would be stored in the "values" list after this program has executed?
values = [45.78, 12.34, 102.14,
5.26, 1034.99] temp1 = 0
values
for num in range(5):
temp1 = values[num] - 0
int(values[num])
values[num] = int(temp1*10) 1
107 Last one, so let's make it difficult! Follow the logic of the code and work out what will
be stored in the two lists after the program has executed.
import math
firstValue = [7.7, 3.2, 5.2, 6.4, 8.9]
secondValue = [9, 6, 4, 12, 10]
for num in range(5):
if round(firstValue[num]) > firstValue[num]:
secondValue[num] = secondValue[num] *
math.ceil(firstValue[num])
else:
secondValue[num] = secondValue[num] *
math.ceil(firstValue[num]) / 2 if secondValue[num] > secondValue
50:
0 0
firstValue[num] = 99firstValue
else: 1 1
firstValue[num] = 0
2 2
3 3
4 4
For the following puzzles, state the output if the following code was added to the above
progr am.
Output
108 print(words[1][0],words[5][3],words[5][4])
111 This puzzle uses substring to extract characters from the words in the 2D list.
print(words[0][3][0:1] + words[0][3][1:].lower()) Output
print(words[first][3].lower(),"",end='')
For the remaining puzzles in this set the following program was written.
grid = [ [5,8,6], [3,4,5], [6,1,0] ]
grid second index
first index 0 1 2
0 5 8 6
1 3 4 5
2 6 1 0
If the code in the following questions was added to the above code state the
output.
for115
first in range(3):
print(grid[first][0]+grid[first][1]+grid[first][2])
Output
print(grid[2][1])
else:
print(grid[2][2])
119 This difficult puzzle displays all nine integers but what order are they displayed in?
for second in range(2,-1,-1):
for first in range(2,-1,-1): Output
print(grid[first]
[second],end='') print()
Output
Mountain Bike
Ski Jacket
Electric Guitar
PS3 - 500Gb
Badminton Racquet
Output
Input Output
Row numbers
Write a program that first asks the user the enter the number
2
of members that have requested to go on the trip. This should
be limited to 20 members. The user should then enter each 3
member's name and the row/seat number they have requested.
4
The program should assume that each member has asked for a
different seat.
Input Output
How many members have requested Bus seats have been booked
a seat? as follows: 0. Empty Empty
5 Empty Empty
Please enter your name. 1. Denzell Empty Hubub
Hubab Empty
Which row would you like to sit 2. Jessica Empty Empty
in? Empty
2 3. Empty Empty Talisha
Which seat number would you Empty
like to sit in? 3 4. Empty Empty Empty Andrew
Thank you, your name has been
added. Please enter your name.
Je ssic a
× 5 members in total
Input
Output
Output
While the max( ) and min( ) functions would normally be used with numerical values
(both integers and floats), they will also work with lists of strings. The minimum and
maximum values will be the first and last alphabetically.
Program Code Output from program
names = ["Bob","Aaliyah","Janet","Dave","Zac"]
The largest value is Zac
print ("The largest value is",max(names))
The smallest value is Aaliyah
print ("The smallest value is",min(names))
Example 44 – sum( )
The sum( ) function adds up numbers in a list and returns that value. It does not work
for strings.
Program Code Output from program
Example 45 – split( )
New lists can be created by splitting a string. The split( ) function searches for a given
character or string and splits the original string each time the search finds a match.
By searching for a space character " " a sentence can be split into its individual words
with each word being stored separately in a new list. Note that, when found, the search
character is removed from the string during the split.
Program Code Output from program
Any character or string can be used in the search. Note that the search string is still
found if it is part of another word.
Program Code Output from program
Example 46 – index( )
The index( ) function finds the first position of a string or character within another string
or list.
Program Code Output from program
The above program outputs the value 6 because the first character is index 0. If you
remember back to the substring explanation near the beginning of the book each
character's position can be defined as shown below.
0 1 2 3 4 5 6 7 8 9
T h o s e w h o
The index( ) function could be used with substring to split a string.
Program Code
milesCycled = [5,8,9,2,4,3,7,4,7,5,9,0]
9 miles
bestDay = 0 were cycled on day 3
average = 0 This was 3.75
bestDay = milesCycled.index(max(milesCycled))
better than the average of 5.25
average = sum(milesCycled)/len(milesCycled)
print (max(milesCycled),"miles")
print ("were first cycled on day",bestDay+1)
print ("This was",max(milesCycled)-average)
print ("better than the average of",average)
Example 48 – append( )
The append( ) function can only be used to add a single item to a list.
Program Code Output from program
compUnits = byte
["byte","Kilobyte","Megabyte"] Kilobyte
compUnits.append("Gigabyte") Megabyte
for each in compUnits: Gigabyte
print(each)
Note that a different style of fixed loop is used in this example. This line would read as:
"for each item in the list compUnits". Each time the loop is executed the next item in the
list is assigned to the loop variable 'each'.
append( ) is useful when creating a list of an unknown length. The programmer can
initialise (create) a single element list and then each new value will simply be appended
(added) onto the end of the list.
Example 49 – extend( )
To add more than one item to a list the extend( ) function should be used.
This effectively joins two lists together.
Program Code Output from program
compUnits = ["byte","Kilobyte","Megabyte"]
byte
compUnits.extend(["Gigabyte","Terabyte"])
Kilobyte
for each in compUnits: Megabyte
print(each) Gigabyte
Terabyte
Example 50 – insert( )
The insert( ) function is used to add new items at a specified index point in a list.
Program Code Output from program
compUnits = byte
["byte","Megabyte","Gigabyte"] Kilobyte
compUnits.insert(1,"Kilobyte") Megabyte
for each in compUnits: Gigabyte
print(each)
In Example 50, “Kilobyte” replaces the item stored at index 1 in the list, which was until
now “Megabyte”.
0 1 2
Byte Megabyte Gigabyte
Kilobyte
Megabyte and Gigabyte move one place in the list, becoming indexes 2 and 3.
0 1 2 3
Byte Kilobyte Megabyte Gigabyte
Example 51 – pop( )
Items can be removed from a list using pop( ) and remove( ).
The pop( ) function removes an item according to its index value. So pop(0) would
remove the first value from the list.
Program Code Output from program
playingCards = 2
["2H","6D","KD","JC","8S"] H
playingCards.pop(3) 6
for each in playingCards: D
print(each) K
If the pop( ) function is used without an index value, the
D last item of the list is removed.
Program Code 8
Output from program
S
playingCards = 2
["2H","6D","KD","JC","8S"] H
playingCards.pop( ) 6
for each in playingCards: D
print(each) K
D
Example 52 – remove( ) J
C
The remove( ) function removes the first example of a named item from a list.
Program Code Output from program
playingCards = 2
["2H","6D","KD","JC","KD"] H
playingCards.remove("KD") 6
for each in playingCards: D
print(each) J
C
Example 53 – random.randint( ) K
D
The randint( ), or random integer function, generates a random integer within a stated
r ange.
Output from program
Program Code
import random 4
for count in range(5): 5
num = 1
random.randint(1,10) 9
print(num) 2
The above program uses a fixed loop to generate five random numbers all with a value
between 1 and 10.
Note that the randint( ) function is part of the random module library. Before the
function can be used in a program, the library must be imported, using:
import random
This is usually done at the beginning of the program.
120 Output
hoursStudied = [2,4,6,3,4,2,3,4,2,3,1]
print("The most hours studied in")
print("a day was",max(hoursStudied))
121 hoursPlayed = [7,3,4,5,2,3,4,8,2,9,10]Output
print("The least hours played in")
print("a day was",min(hoursPlayed))
122
weight = [12,8,3,7,14,6]Output
totalWeight = sum(weight)
print("The total weight is:",totalWeight)
123
numList = [3,8,30,72,3,7,7,23,41,99,2,1,8,92]Output
limits = [ ]
limits.append(min(numList))
limits.append(max(numList))
manPlusMax = sum(limits)
print("Minimum",limits[0],"+ Maximum",limits[1],"=",manPlusMax)
124
numList = [3,8,30,72,3,7,7,23,41,99,2,1,8,92]Output
limits = [ ]
limits.append(numList[0])
limits.append(numList[3])
limits.append(numList[6])
limits.append(numList[7])
limits.append(numList[10])
print("Maximum =",max(limits))
print("Minimum =",min(limits))
125
shoppingList = "Peas,Carrots,Milk,Tea Bags,Bread,Marmalade"
shopping = shoppingList.split(",")Output
for each in shopping:
print(each)
126
cricketScores = "2,3,0,0,0,1-0,0,0,2,3,0-1,1,0,0,0,6"Output
overScores = cricketScores.split("-")
for loop in range(len(overScores)):
oneOver = overScores[loop]
print("The first ball =",oneOver[0:1])
wordPosition = vocals.index("shout")
print("The word is at position",wordPosition)
132 sentence = "Here's looking at you, kid." Output
words = sentence.split(" ")
wordPosition = words.index("at")
print("The word is at position",wordPosition)
Puzzle set 13 – Predefined functions (pop, insert, remove,
extend and append)
These next puzzles are like the card trick where you are shown three cards, you choose
one and they are then swapped around and you have to guess where your chosen card is.
Keep an eye on how each function changes the list. You may find it useful to make notes
on paper to help you.
For each puzzle, state what will be displayed at the end when the program is executed.
133 Output
light = [2,4,6,8,10]
light.pop(2)
light.append(7)
print(light)
light.pop(3)
light.pop(3)
light.remove(1)
print(light)
GCSE, iGCSE, National 4/5 and Higher 93
Section 5 – Predefined functions
points = [3,4,5,1,3,1,4]
141 Output
above = []
average = sum(points)/len(points)
for loop in range(len(points)):
if points[loop] > average:
above.append(points[loop])
print(above)
142 And finally a very difficult one. State what is stored and displayed in list "three".
one = [3,4,5,1,5,1,4,3] Output
two = []
three = []
for loop in
range(len(one)-1,-1,-1):
two.append(one[loop])
for loop in
range(len(one)):
if one[loop]==two[loop]:
three.append(1)
else:
three.append(0)
print(three)
Input Output
Input
Output
Stock = [12,10,8,10,12,14,16,20,12,12,8]
The largest dress in stock is size 20
The smallest dress in stock is size 8
Output
nameList = [["Matthew","Reid"]]
numNames = int(input("How many names do you
wish to add?")) for names in range(numNames):
newForename = str(input("Please enter a
forename"))
newSurname = str(input("Please enter a
surname"))
nameList.append([newForename,newSurname])
displayNames(nameList)
# Main Program
scores =
[4,6,8,5,6,3,5,9,10,2,4,6,
3,5]
When writing procedural programs in Python, the defined modules are usually written
displayScoreData(scores)
at the beginning of the program.
When a procedure is called, for example, "displayScoreData(scores)", any variables or
lists that will be used by the module are passed as parameters. Parameters are placed
within the brackets of the call statement and the brackets of the def( ) statement.
The parameters in the procedure definition are different from the parameters in the
call from the main program. This is useful when we wish to use a module with different
variables and lists.
■
The parameters in the procedure call are called "actual" parameters.
■
The parameters in the procedure definition are called "formal" parameters.
When a procedure or function is called, the actual parameters are copied into the formal
par ameter s .
It is possible to use the result returned from a function without assigning it. For
example, the last two lines of the example program could be written in one line of code:
print("Repayment amount =", round(interestCalculator(amount,years,intere
Example 58 – Scope
The following program displays the average, calculated in the procedure, in two
different places:
1 within the procedure
2 within the main program.
When this program executes, a list, "scores", is passed into the procedure where the
(mean) average of the values in the list is calculated and displayed. At the bottom of
the main program (after the procedure has been called and the average calculated) the
average is displayed again.
While you would expect that the same average (5.4) would be displayed twice, the
average displayed in the main program is 0.
This anomaly occurs because any variable or list that is initialised (created) within a
procedure only exists within that procedure. The scope of the "average" variable within
the procedure is said to be local.
The "average" variable initialised in the main program is said to have global scope as it
can be used anywhere in the main program.
Good coding separates out as many reusable blocks of code as possible. The purpose of
parameter passing is to share the data between modules and the main program. Functions
return values as this allows the results of the calculation or task to exist outside the
f unc tion.
144num1 = 8 Output
num2 = 3
value = module4(num1,num2)
print(value)
145num1 = 100 Output
num2 = 6
num3 = 9
print(module2(num1) + module3(num2,num3))
146num1 = 5Output
num2 = 10
temp = int(module2(num2))
value = module3(temp,num1)
print(value)
147num1 = 2Output
num2 = 5
num3 = 8
module1(num1,module3(num1,num2),module2(5*num3))
Puzzles 148 to 155 contain code that calls the following functions. The functions return
different values depending on the parameters passed in.
def textChanger1(word):
wordLength = len(word)
if wordLength <=2:
return word
elif wordLength>2 and
wordLength<=6:
temp1 = word[0:2]
temp2 = word[len(word)-2:]
word = temp2 + word + temp1
return word
else:
temp1 = word[0:3]
temp2 = word[len(word)-3:]
print(temp1,temp2)
word = temp2 + temp1
return word
def textChanger2(word):
if word.lower() == word:
return word.upper()
elif word.upper() == word:
return word.lower()
else:
return "mixed"
def textChanger3(word):
length = 5 * len(word)
word = str(length-5) + word +
str(length) return word
For each of the following puzzles write down the output that would be
password = textChanger2(password)
password = textChanger3(password)
print("Password is",password)
152password = "xu" Output
password = textChanger3(password)
password = textChanger2(password)
password = textChanger1(password)
print("Password is",password)
Read to file
TXT
Note: If you wish to research reading and writing from databases, you will need to install
Python's MySQL Connector library. Instructions on how to set this up and connect to/
communicate with a database file are available online. Later versions of Python may have
SQLite built into the installation so check your version first.
eyeColour = blue
["blue","brown","green"] brown
with open('eyes.txt','w') as green
eyeColourFile: for each in
eyeColour:
The above program opens a write only
eyeColourFile.write(each + connection "w" to a text file called "eyes.txt".
A"\n")
loop is then used to write each element of a list to the file using the connection
"eyeColourFile" and the function write( ).
Note that the string "\n" is concatenated onto the end of each line. This is an "end-of-line"
character. When a text file is opened the \n character ensures that the next item of text
appears on a new line.
eyes.txt - Notepad
File Edit Format View Help
blue
brown
with \n green
eyes.txt - Notepad
eyes.txt File Edit Format View Help
without \n bluebrowngreen
If the text file does not exist when a write only connection is attempted, an empty file
will be created.
The connection to the file is closed at the end of the with open( ) statement.
Note that even if this program were executed lots of times, the file would still store the
colours. The "w" connection type means that the previous information is overwritten
each time the program is executed.
hairColour = blue
["brown","red","white","black","blonde brown
"] with open('eyes.txt','a') as green
hairColourFile: brown
for each in hairColour: red
The above program opens an append connection "a" to
hairColourFile.write(each+"\n") white
the file "eyes.txt" used in Example 60. As before, a loop black
is used to write all the items of a list to the file. This time blonde
the list items are appended to the end of the file.
Note that each line has been split using a space character as there is a space between
each word in the file. This can be replaced with a comma where the file information is
comma separated as with .csv files.
forename = [] Matthew,Reid,Schmeed/n
surname = [] Niall,Dowds,Jas/n
nickname = [] Emir,Duman,Meter/n
with Lewis,Carter,Momo/n
open('Friends.csv','r') as Steven,Moyles,Beve/n
pals: for each in
pals.readlines():
Output from program
each = each[0:-1]
temp = each.split(",") ['Matthew','Niall','Emir','L
forename.append(temp[0]) ewis','Steven']
surname.append(temp[1]) ['Reid','Dowds','Duman','Car
nickname.append(temp[2]) ter','Moyles'] ['S c h m e e
print(forename) d','J a s','M e t e r','M o
print(surname) m o','B e v e']
print(nickname)
156 bikes =
["Perseid","Lomond","Retford","Timbuktu"]
count = 1Output with
open('bikes.txt','w') as bikeFile:
for each in bikes:
bikeFile.write(str(count) + ". " + each
+ "\n")
157 count = count + 1
sizes = ["12","23","16","08"]
moreSizes = ["10","20",]Output
with open('sizes.txt','w') as sizeFile:
for each in moreSizes:
sizeFile.write(str(each)+"\n")
with open('sizes.txt','a') as sizeFile:
for each in sizes:
158
sizeFile.write(str(each)+"\n")
keys = ["q","w","e","r"]
keysTwo = ["a","s","d","f"]Output
with open('keyboard.txt','w') as
keysFile:
for each in keys:
keysFile.write(each)
159with
The file "elements.txt" is shown below. as
open('keyboard.txt','w')
keysFile:
elements.txt
for each in keysTwo:
keysFile.write(each)
Oxygen
Neon
Mercury
George
Washington
John Adams
Thomas
Jefferson
State
James theMadison
output from the following program.
presidents = []
with Output
open('presidents.txt','r') as
pres: for each in
pres.readlines():
each = each[0:-1]
presidents.append(each)
for loop in
161 Using the same presidents.txt file, state the output from the following program.
range(len(presidents)):
print(presidents[loop])
presidents = ["James Monroe","John
Quincy Adams"] with
open('presidents.txt','r') as pres: Output
for each in pres.readlines():
presidents.append(each[0:-1])
for loop in range(len(presidents)):
print(str(loop+1)+".
162 The file 'RCaverages.csv' is shown below.
"+presidents[loop])
RCaverages.txt
K e v i
n,98.2
I n n e
s,97.3
A l e
x,97.7
Ja c k
i
e,92.9
I n n e
s,98.1
IfAthe lusereenters "Alex", state the output from the following program.
scores
x,97.3 = [] Output
name
G r e= str(input("Please enter a name"))
with
g,98.5 open('RCaverages.csv','r') as allScores:
for each in allScores.readlines():
K e v i
each = each[0:-1]
n,96.6
temp = each.split(",")
Aif temp[0]
l e == name:
x,97.8
scores.append(temp[1])
G r e
print("The scores for",name,"were:")
for loop
g,98.5 in range(len(scores)):
print(scores[loop])
163 The file "longJumps.txt" is shown below.State the output from the following progra
S u m m a -7.2 3
-7.3 4 - 8.11-
8.0 8 Petra-6.92-
7.33-7.92-7.55 K
yl i = []Output
names e -7.5 5
jump
-7.4 = 1-7.9
[] 9 -
8.1 3open('longJumps.txt','r') as longJs:
with
for eachPerson in longJs.readlines():
eachPerson = eachPerson[0:-1]
temp = eachPerson.split("-")
names.append(temp[0])
longest = max(float(temp[1]), float(temp[2]),
float(temp[3]), float(temp[4])) jump.append(longest)
for loop in range(len(jump)):
print(names[loop],jump[loop])
164 And finally, a very difficult puzzle. Well done if you get this
one. The files "num1.txt" and "num2.txt" are shown below.
num1.txt num2.txt
10,2 1,2,
0,3 0,4 3,4
0 2 0,3 2,3,
0,4 0,5 4,5
0 3 0,4 3,4,
State the
0,5 0,6 output from the following program.
5,6
temp1List
0 4 0,5 = [] 4,5,
Output
temp2List
0,6 0,7 = [] 6,7
with
0 open('num1.txt','r') as numbers:
for eachNum in numbers.readlines():
eachNum = eachNum[0:-1]
temp = eachNum.split(",")
temp1List.append(temp)
with open('num2.txt','r') as numbers:
for eachNum in numbers.readlines():
eachNum = eachNum[0:-1]
temp = eachNum.split(",")
temp2List.append(temp)
with open('num3.txt','w') as numbersOut:
for loop in range(0,2):
numbersOut.write(str(temp1List[loop][0])+"\n")
for loop in range(2,4):
numbersOut.write(str(temp2List[loop][3])+"\n")
total = 0
with open('num3.txt','r') as numbers:
for eachNum in numbers.readlines():
total = total + int(eachNum[0:-1])
print("Total =",total)
Input
Output
Please enter the The average temperature for
starting week 13 weeks 13 to 17 12.72 degrees
Please enter the final
week
17
Program 69 – Garage sale
When people want to get rid of unwanted items in their house, they sometimes have
a garage sale. A program is required to store garage sale items and their prices. The
program should have a main program and two procedures:
1 Each time the program starts, users are asked to enter a description of an item for sale
and the item's price. Each description and price entered should be added to any previous
information stored in a text file. The user should continually be asked to enter more
items until the user enters a "trigger" input that stops the program asking for the
next item.
2 The program should then display a list of every stored items' description and price.
Input Output
1 e2-e4, e7-
e5\n
2 d2-d4,
e5xd4\n
3 c2-c3,
d4xc34\n
4 Bf1-c4,
A program is required to read a chess game from the file called "chessGame.txt" and
c3xb2\n
display 5 the standardQd8-
Bc1xb2, chess notation in a more readable way. To do this, some characters in
the fileg5\n
should6 be removed and other characters should be changed to words:
Ng1-f3,
- = toBf8-b4+\n
x = takes + = check
For example:
5. Bc1xb2, Qd8-g5
would become
Move 5 Bc1 takes b2 Qd8 to g5
Output
Move 1 e2 to e4, e7 to e5
Move 2 d2 to d4, e5 takes d4
Move 3 c2 to c3, d4 takes c34
Move 4 Bf1 to c4, c3 takes b2
and so on for the remaining moves
Cineworld,99,1008,23.6\n
A program is required to read the file data into a 2D list and then display the following
infor mation:
■
The company that has the most cinema screens in the UK.
■
The name of the company that has the highest percentage of total screens.
■
Program 72number
The average – Yearly temperatures
of screens (part has
each company 2) at each building.
Open Program 68. Edit the program as follows:
■
After asking for a range of weeks, the main program should ask for a day of the week.
■
A procedure should be written to:
• store the temperatures for the selected day (for all 52 weeks) in a list
• calculate the minimum and maximum temperatures in the list
• display the maximum and minimum temperatures.
■
The main program should then ask the user to enter a temperature.
■
A function should be written to:
• calculate the number of times the entered temperature is found in the entire file
of data
Input Output
• return and display the result in the main program with a suitable message.
Please enter the The average temperature for weeks
starting week 13 13 to 17 12.72 degrees
Please enter the final The min and max temperatures in day
week 4 were
17 -3 and 27
Please enter a day of There were 47 occasions that the
the week 4 temperature was 6 degrees.
Please enter a
temperature
6
Running total
A running total uses a loop to add up a set of values. These may be entered by the user or
read in from an external file.
def runningTotal(fileName):
total = 0
fileName = fileName + ".txt"
with open(fileName) as nums:
for each in nums.readlines():
each = each[0:-1]
total = total + int(each)
return total
fileName=str(input("Which file would you
like to add up?")) total =
runningTotal(fileName)
print("The total =",total)
Output from program
Input validation
Good programming ensures that only valid user inputs are entered into a program. If
incorrect data is entered, the user should be informed of their error before being asked to
input the data again.
Traversing a list
Traversing simply means accessing each element of a list one at a time. This may be to
display the data or process the stored data in some way.
Linear search
A linear search algorithm returns whether or not a value exists in a list, or the position of a
value if it is found.
numbers = [[12,3,5,4],[67,7,5,3],[5,7,3,2],[4,6,5,8],
State the value to
[5,3,2,4],[5,7,8,9],[0,9,2,3],[6,4,6,2],[4,5,7,86],[7,4,4,6]]
count 3
occurrence = 0 3 appeared 5 times
target=int(input("State the value to count"))
for outerLoop in range(len(numbers)):
for innerLoop in range(len(numbers[outerLoop])):
if numbers[outerLoop][innerLoop] == target:
occurrence = occurrence + 1
print(target,"appeared",occurrence,"times")
Find maximum
Python has a predefined function max( ), which returns the maximum value in a list as
shown below:
numbers =
[12,3,5,4,67,7,5,3,5,7,3,2,4,6,5,8,8
6,4,4,9] print("Maximum value
Despite this, the algorithm for finding the maximum value in a list is so common that it's
is:",max(numbers))
worth learning. Once you know the algorithm you can adapt it in ways that you can't with a
predefined function.
names = ["Agattha","Elsebe","Ranneigh","Kolka","Magga"]
ages = [22,33,51,49,18]
print("Oldest person is:",names[findMaxPosition(ages)])
Find minimum
The find minimum algorithm requires only one simple change to the condition in the "if"
statement as highlighted above. By changing the greater than symbol (>) to a less than
symbol (<) the smallest value is found instead.
names =
["Agattha","Elsebe","Ranneigh","Kolka",
"Magga"] ages = [22,33,51,49,18]
print("Youngest
is:",names[findMinPosition (ages)])
Bubble sort
A bubble sort moves through pairs of elements swapping values where the values are in
the wrong order.
7 1 10 26 4 5
×
As the loop variable increments (up to the second last element), pairs of elements are
checked in turn. If the values are in the wrong order they are swapped; if they are in the
correct order they are left where they are.
0 1 2 3 4 5 0 1 2 3 4 5
1 7 10 26 4 5 1 7 10 26 4 5
0 1 2 3 4 5 0 1 2 3 4 5
1 7 10 26 4 5 1 7 10 4 26 5
× ×
When the list has been traversed once, it is still not sorted. The outer loop ensures that
the list is traversed multiple times until all the values are in order.
0 1 2 3 4 5
1 7 10 4 5 26
An insertion sort traverses a list from element index 1 to the end of the list. During this
the following algorithm is followed:
1 As the list is traversed, the contents of the next element are temporarily copied into a
variable called "currentScore".
0 1 2 3 4 5
7 5 1 26 4 5
currentScore
0 1 2 3 4 5
2 The temporary value stored in this variable
7512645
is compared to each element before the
original position of the temporary value.
This continues, working backwards 5
through the list, until either of the
following rules is true:
●
the temporary value is greater than the next value
●
or the start of the list is reached.
Each value that is found to be larger than the temporary value is copied into the next
element.
3 When one of the rules is true – for example, when the start of the list is reached – the
temporary value is copied into that element.
0 1 2 3 4 5
7 7 1 26 4 5
Steps 1 to 3 are now repeated for the element at index 2 in the list. In this case both
elements at indexes 0 and 1 are larger than the temporary value, so both are copied into
the next element.
0 1 2 3 4 5 0 1 2 3 4 5
5 7 1 26 4 5 5 5 7 26 4 5
1 1
currentScore
Again, the start of the list is reached and the temporary value is copied into element 0.
0 1 2 3 4 5
5 5 7 26 4 5
Steps 1 to 3 are now repeated for the third element. As 26 is already greater than the
element to the left no change is made to the list.
0 1 2 3 4 5
1 5 7 26 4 5
26
currentScore
Steps 1 to 3 are now repeated for element 4. This time the temporary value is found to
be greater than the element at index 0. This means that the inner loop stops at this point
and the temporary value is copied into the element at index 1.
0 1 2 3 4 5 0 1 2 3 4 5
1 5 7 26 4 5 1 5 5 7 26 5
4 4
currentScore
0 1 2 3 4 5
1 5 5 7 26 5
Note that as the list is traversed the values before the current position are always sorted
in the correct order.
The list will be completely sorted with one final execution of steps 1 to 3.
Binary search
A binary search works by continually halving a list until its finds (or doesn’t find) a target
value. the list must already be sorted for a binary search to work.
The above example has a list of 12 names in alphabetical order. In run 1, the user has
entered “Dennis” as the target name to find in the list.
A binary search algorithm uses three values:
■
low – the lowest index of the elements still to be checked
■
high – the highest index of the elements still to be checked
■
mid – the index halfway between the low and high indexes.
When the search begins, the low and high indexes are the first (0) and last (11) elements
of the list. The midpoint is calculated as (0 + 11) / 2 = 5.5. As a list index must be an integer,
the int( ) function is used to convert 5.5 to an integer. The midpoint is therefore 5.
target = Beth mid = int
(low + high)/2
low high
0 1 2 3 4 5 6 7 8 9 10 11
Aaron Beth Clive Dennis Egbert Francis Gillian Hugh Icarus Jeremy Kyle Lachi
If the name at the midpoint is greater than the target (“Francis” comes after the target
“Dennis” alphabetically) then the target must come before the midpoint in the list
(between indexes 0 to 4). In this case, high is reset to one less than the midpoint and a
new midpoint is calculated.
mid = int
(low + high)/2
low high = mid − 1
0 1 2 3 45 6 7 8 9 10 11
Aaron Beth Clive Dennis Egbert Francis Gillian Hugh Icarus Jeremy Kyle Lachi
If the value at the midpoint is less than the target (“Clive” comes before the target
“Dennis”) then the target must come after the midpoint in the list (between indexes 3 to 4).
In this case, low is reset to one more than the midpoint and a new midpoint is calculated.
low = mid + 1
high
0 1 2 3 4 5 6 7 8 9 10 11
Aaron Beth Clive Dennis Egbert Francis Gillian Hugh Icarus Jeremy Kyle Lachi
If the value stored at the mid element is equal to the target, the algorithm returns the
index where the target was found (3). This is used to display Dennis’ age, stored in the
list “ages”.
Note that at the beginning of the program position is set to −1. If the target is not found
in the list, low + 1 or high −1 will eventually result in low being greater than high. This
is the condition that stops the while loop. If the while loop exits without the target being
found, −1 is therefore returned as the position. This is used in the main program to
display “Name not found”.
Project 1 – Speeding
Description of problem
An insurance company is conducting a survey to determine whether
drivers of newer cars are more likely to break the speed limit than
drivers of older cars. An employee of the insurance company will
sit with a tablet beside a speed warning sign. When the warning
sign lights up, the employee will record that the car was breaking
the speed limit. If the warning sign does not light up, the employee
will record that the car was not breaking the speed limit.
The age of the car will also be recorded for all cars. A program is
required to store this information and analyse the results.
Functional requirements
(a list of what the program should do)
The required program should:
■
Read in previously recorded data from a text file when the
program starts. If no previous data exists, the program should
create an empty text file.
■
Ask the user to continually enter each car's age and speeding data until the user enters
999 for the age. The data for each car should be added onto the previously recorded data.
■
Display the percentage of cars that were breaking the speed limit.
■
Display a list of car ages showing how many of each age were caught speeding.
■
Display the age of car that was caught speeding more times than any other age of car.
■
Before the program finishes executing, the up-to-date data should be written back to
the text file, overwriting the previous data.
136 How to Code in Python
Section 9 – Large project tasks
Input s
The program should receive the following inputs:
■
Car data from the file will be inputted with the following format:
age,speeding,end-of-line
Outputs
for example, 1 = speeding, 0 = not speeding.
■
The program
A value should
to stop produceasking
the program the following
for moreoutputs:
car data
■
forWhen
example, 999. the percentage of cars that were breaking the speed limit, the output
displaying
should be formatted as follows:
Speeding – 34%
1 – 20
2–6
3–0
4 – 65
5 – 28
6 – 12
7 – 89
… and so on.
Additional challenging task
Note that every car, from the youngest to the oldest, should be displayed
Write an additional module that works out if new cars speed more than older cars. You will
■
When
have displaying
to consider thethe age of car
following that was caught speeding the most, the output should be
questions:
formatted
■
as follows:
At what age should the cut-off point be between old and new cars?
7-year-old
■
cars were the worst speeding offenders.
■
How will I account for the fact that there may be many more older cars passing than
When writing the car data back to the text file, the following format should be used:
newer cars, or vice-versa?
age comma speeding end-of-line GCSE, iGCSE, National 4/5 and Higher 137
For example, "10,1/n"
Section 9 – Large project tasks
A program is required to analyse the file and provide the information required for the
newspaper article.
Functional requirements
(a list of what the program should do)
The required program should:
■
Input data from the file "GE2017.csv" when required.
■
Provide a list of safe constituencies for Conservatives and Labour.
■
Provide a list of close constituencies sorted by closest first.
■
State how many times more than 200 voters spoiled their ballot paper in a constituency.
Input s
The program should receive the following inputs:
■
Voting data from the file will be inputted with the following format:
Constituency, Country, Total Possible Voters, Votes, Invalid Votes, Conservative, Labour
end-of-line
Outputs
For example, "Aberavon,Wales,49892,33268,57,5901,22662/n"
Ashford England
……
■
A list of safe Labour constituencies should be displayed as shown below:
Aberavon Wales
Barking England
……
■
A list of close constituencies should be displayed as shown below:
Kensington 20
Additional
Dudley challenging
North 22 task
Write an additional procedure
Newcastle-under-Lyme 30 that will display a list of constituencies where less than 50%
of voters voted for the two main parties. The output should be grouped by country.
Southampton, Itchen 31
■
Note that in some constituencies, 0 votes were registered for Conservative and Labour.
These constituencies should not be displayed.
■
The number of constituencies with more than 200 invalid votes should be displayed:
Functional requirements
(a list of what the program should do)
The required program should:
■
Merge the names and scores from three tournaments (each with different competitors)
into one list sorted by score.
■
Identify the top 30 archers from the merged list.
■
Randomly select another 5 archers who have
●
scored more than 650
●
Input
are not insthe top 30 archers.
■
The program
Display theshould
top 30receive
scorersthe
andfollowing inputs:
five selected archers in alphabetical order of surname.
■
Data from three files "americas.txt", "asia.txt" and "europe.txt". The file data will be
formatted as: