igcse_compsci_2ed_python_sol
igcse_compsci_2ed_python_sol
Sample answers have been written by the authors. In examinations, the way marks are awarded may be different. References to
assessment and/or assessment preparation are the publisher’s interpretation of the syllabus requirements and may not fully reflect
the approach of Cambridge Assessment International Education.
A note about identifiers in pseudocode: The identifiers, which include variable, procedure and function names, given in exam
questions will be in mixed upper case, for example, NumberOfPlayers. When using pseudocode to answer questions you must
use the exact same variable name for any variables given in the question. When you are creating your own variable names in your
pseudocode answers, it is quite normal to use the syntax that is used in your preferred programming language, for example in
Python, number_of_players. You must ensure that your algorithm is correct and unambiguous and that the identifiers chosen are
consistent throughout your solution.
Solutions
Chapter 1: Python 3
Practice tasks
1.1 (Answer provided in text.)
Challenge tasks
1.1 # two_inputs.py
first = input('What is your first name? ')
last = input('What is your last name? ')
print('Hi', first, last)
1.2 # triangle.py
from turtle import *
forward(100)
right(120)
forward(100)
right(120)
forward(100)
1
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
End-of-chapter tasks
1 age = input('What is your age? ')
name = input('What is your name? ')
print('Hi ' + name + '. You are ' + age + '.')
forward(100)
left(90)
forward(50)
left(45)
forward(70)
left(90)
forward(70)
left(45)
forward(50)
hideturtle()
forward(100)
left(72)
forward(100)
left(72)
forward(100)
left(72)
forward(100)
left(72)
forward(100)
2
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
2.2 # remainder_machine.py
# End nicely by waiting for the user to press the return key.
input('\n\nPress RETURN to finish.')
2.3 # square.py
from turtle import *
forward(d)
right(90)
forward(d)
right(90)
forward(d)
right(90)
forward(d)
Challenge tasks
2.1 # sphere.py
# End nicely by waiting for the user to press the return key.
input('\n\nPress RETURN to finish.')
3
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
2.2 # grass_seed.py
# End nicely by waiting for the user to press the return key.
input('\n\nPress RETURN to finish.')
2.3 # hexagons.py
from turtle import *
forward(d)
right(60)
forward(d)
right(60)
forward(d)
right(60)
forward(d)
right(60)
forward(d)
right(60)
forward(d)
End-of-chapter tasks
1 # dice.py
import random
2 # time.py
time24 = float (input('Provide the time in the form 18.25: '))
if time24 < 13.0:
print(time24) # The input is in the correct format
else:
print(round(time24 - 12, 2))
4
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
3 a
# triangle.py
from turtle import *
forward(s)
left(120)
forward(s)
left(120)
forward(s)
b
# isosceles.py
from turtle import *
left(180-A)
forward(s)
left(2*A)
forward(s)
right(180-A)
goto(0,0)
3.2 3
5
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
3.3
START
INPUT
number1
number2
OUTPUT
answer
STOP
Chapter 4: Subroutines
Practice tasks
4.1 a 11 b 11
4.2 # square.py
from turtle import *
def square(side_length):
forward(side_length)
right(90)
forward(side_length)
right(90)
forward(side_length)
right(90)
forward(side_length)
square(100)
6
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
4.3 # number_squared.py
def number_squared(number):
return number * number
print(number_squared(2))
4.4 # highest_number.py
print(highest(4, 2))
4.5 # password_number.py
def check_passcode(passcode):
if passcode > 999 and passcode <10000:
return 'PASS'
else:
return 'FAIL'
print(check_passcode(1413))
4.6 # circle.py
def circle_properties(radius):
circumference = 2 * 3.142 * radius
area = 3.142 * radius * radius
c,a = circle_properties(50)
print('Circumference:', c, '\nArea:', a)
4.7 # global_name.py
def edit_name(new_name):
global name
name = new_name
return name
7
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
4.8 a
import turtle module
PROCEDURE draw_star
forward(50)
right(144)
forward(50)
right(144)
forward(50)
right(144)
forward(50)
right(144)
forward(50)
ENDPROCEDURE
CALL draw_star
b # star.py
from turtle import *
def draw_star():
forward(50)
fight(144)
forward(50)
right(144)
forward(50)
right(144)
forward(50)
right(144)
forward(50)
draw_star()
Challenge tasks
4.1 # flower.py
from turtle import *
circle(50)
right(72)
circle(50)
right(72)
circle(50)
right(72)
circle(50)
right(72)
circle(50)
8
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
4.2 # circle2.py
def circle_properties(radius):
circumference = 2 * 3.142 * radius
area = 3.142 * radius * radius
return circumference, area
2 The function is going to change the value of the global variable so player_score must be
re-declared with the global keyword. This acts as a warning to the programmer that their
function is going to alter the value of a variable that is outside the scope of the function and
so that the programmer can be sure that this is what is intended.
3 The keyword global is not required if the function is just accessing the value of the variable
and not altering it.
End-of-chapter tasks
1 A pseudocode solution:
FUNCTION time
mins seconds // 60
secs seconds % 60
RETURN mins, secs
ENDFUNCTION
time_in_seconds 190
m,s time(time_in_seconds)
OUTPUT m, s
A Python solution:
def time(seconds):
mins = seconds // 60
secs = seconds % 60
return mins, secs
time_in_seconds = 190
m,s = time(time_in_seconds)
print(m, 'minutes', s, 'seconds')
9
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
2 A pseudocode solution:
FUNCTION to_mph(kph)
mph kph / 1.60934
RETURN mph
ENDFUNCTION
speed_kph 80
OUTPUT to_mph(speed_kph)
A Python solution:
def to_mph(kph):
mph = kph / 1.60934
return mph
speed_kph = 80
print(to_mph(speed_kph))
3 A pseudocode solution:
PROCEDURE square
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
ENDPROCEDURE
CALL square
right(60)
CALL square
right(60)
CALL square
right(60)
CALL square
right(60)
CALL square
right(60)
CALL square
A Python solution:
def square():
forward(100)
10
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
right(90)
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
square()
right(60)
square()
right(60)
square()
right(60)
square()
right(60)
square()
right(60)
square()
4 A pseudocode solution:
h 10
w 8.3
l,t paint(h,w)
OUTPUT l, t
A Python solution:
h = 10
w = 8.3
l,t = paint(h,w)
print('litres:', l, '\ntins:', int(t))
11
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
# Two frames
frame1 = Frame(window,height=20,width=100,bg='green')
frame1.grid(row=1, column=0)
frame2 = Frame(window,height=20,width=100,bg='red')
frame2.grid(row=1, column=1)
# A drop-down menu
options = (1,2,3)
my_variable_object = IntVar() # access the value with .get()
my_variable_object.set('choose:')
my_dropdown = OptionMenu(window, my_variable_object, *options)
my_dropdown.grid()
5.2 a sticky=W
b sticky=E
c There are only two letters that need changing in Code snippet 5.6, which are highlighted below.
# Add two radiobutton widgets
# Use optional sticky argument to align left
radio1 = Radiobutton(window, text='Female', variable=gender,
value='female')
radio1.grid(row=2, column=0, sticky=E)
radio1.select() # pre-selects this this radiobutton for the user
12
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
radio2 = Radiobutton(
window, text='Male', variable=gender,
value='male')
radio2.grid(row=3, column=0, sticky=E)
5.3 # drop-down.py
from tkinter import *
def change_text():
my_label.config(text=my_variable_object.get())
Challenge tasks
5.1 # two-way-converter.py
from tkinter import *
def to_mph():
if kph_textbox.get() != '': # Not essential
kph = float(kph_textbox.get())
mph = kph / 1.60934
mph_textbox.delete(0, END)
mph_textbox.insert(END, mph)
def to_kph():
if mph_textbox.get() != '': # Not essential
mph = float(mph_textbox.get())
13
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
# Add a frame
button_frame = Frame(window, height=4, width=4)
button_frame.grid(row=1, column=1)
End-of-chapter tasks
1 from tkinter import *
def change_text1():
my_label.config(text='Hello World')
def change_text2():
my_label.config(text='Bye Bye')
14
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
def change_text1():
my_label.config(text='Hello World')
def change_text2():
my_label.config(text='Bye Bye')
def change_text2():
my_label.config(text='2')
def change_text3():
my_label.config(text='3')
15
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
def change_text4():
my_label.config(text='4')
def change_text5():
my_label.config(text='5')
def change_text6():
my_label.config(text='6')
def change_text7():
my_label.config(text='7')
def change_text8():
my_label.config(text='8')
def change_text9():
my_label.config(text='9')
# Add a frame
frame1 = Frame(window, height=20, width=60)
frame1.grid(row=1, column=0)
16
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Distance = 15 miles
(The Speed and Distance must be assigned values before Time can be calculated. Be aware that
kilometres and miles are different distances.)
6.2 The flowchart does not indicate what units are being used for distance and speed or what units the
journey time should be given in.
b A Python solution:
from turtle import *
forward(length)
left(120)
forward(length)
left(120)
forward(length)
17
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b Pseudocode: UPPER(my_string)
Python: my_string.upper()
e Pseudocode: LENGTH(my_string)
Python: len(my_string)
Challenge tasks
6.1 a A Python solution:
distance = int(input('Distance between airports in km: '))
speed = int(input('Speed of aircraft in km/hr: '))
print(journey_time, 'hours')
b It is unclear how the journey time should be output. Hours to decimal places is what was
chosen but hours and minutes would have been better. Or perhaps the answer was only
required to the nearest hour.
6.2 In the input() function, it is intended that three strings are joined. As a+b is not a string it
cannot be joined to other strings. Here is a solution to the problem:
confirm = input('Is the sum of your two numbers ' + str(a+b) + '?')
End-of-chapter tasks
1 a is used for showing inputs and outputs in algorithms.
b is used for general processes in algorithms such as calculations or assigning values to
variables.
c is used to show termination of the algorithm - either START or STOP.
2 my_string = str(5*2)
18
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b A Python solution:
OUTPUT
name = input('Your name: ') name,
time1 = float(input('First 100m time: ')) average, pb
time2 = float(input('Second 100m time: '))
time3 = float(input('Third 100m time: '))
time4 = float(input('Fourth 100m time: '))
time5 = float(input('Fifth 100m time: ')) STOP
average = (
time1 + time2 + time3 + time4 + time5) / 5
average = round(average, 2)
pb = min(time1, time2, time3, time4, time5)
19
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Chapter 7: Selection
Practice tasks
7.1 discount = 0.5
if child == 'y':
ticket_price = ticket_price * discount
7.2 Python uses the equals sign as the assignment operator instead of the symbol that is used
in pseudocode. This means Python cannot use a single equals sign for the “is equal to” logical
operator and so uses two equals signs instead.
IF number2 = number1
THEN
OUTPUT 'Match'
ELSE
OUTPUT 'No match'
ENDIF
20
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INPUT
number1
number2
FALSE TRUE
OUTPUT number2 = OUTPUT
"No Match" number1 "Match"
STOP
b A Python solution:
number1 = int(input('Enter first number: '))
number2 = int(input('Enter second number: '))
if number2 == number1:
print('Match')
else:
print('No Match')
21
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INPUT
number1
number2
FALSE TRUE
OUTPUT number2 > OUTPUT
"Acceptable" number1 * 2 "Too Large"
STOP
b A Python solution:
number1 = int(input('Enter first number: '))
number2 = int(input('Enter second number: '))
if number2 > number1 * 2:
print('Too Large')
else:
print('Acceptable')
22
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INPUT
number1
number2
FALSE TRUE
OUTPUT number1 MOD OUTPUT
"Not a Factor" number2 = 0 "Factor"
STOP
b A Python solution:
number1 = int(input('Enter first number: '))
number2 = int(input('Enter second number: '))
if number1 % number2 == 0:
print('Factor')
else:
print('Not a Factor')
23
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
7.7
START
INPUT
number1
number2
number2 = TRUE
OUTPUT
number1 'Same'
FALSE
TRUE
number2 > OUTPUT
number1 'Second'
FALSE
FALSE
STOP
24
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INPUT
full_price
age
TRUE
age >= 18 final_price ← full_price
FALSE
TRUE
age >= 15 final_price ← full_price * 0.8
FALSE
FALSE TRUE
final_price ← 0 age >= 4 final_price ← full_price * 0.6
OUTPUT
final_price
STOP
25
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
INPUT full_price
INPUT age
IF age >= 18
THEN
final_price full_price
ELSE
IF Age >=15
THEN
final_price full_price * 0.8
ELSE
IF Age >=4
THEN
final_price full_price * 0.6
ELSE
final_price 0
ENDIF
ENDIF
ENDIF
OUTPUT final_price
b A Python solution:
full_price = float(input('Enter full ticket price: £'))
age = int(input('Enter passenger age: '))
26
27
7.9 a
ENDCASE
CASE month
OTHERWISE
INPUT LOWER(month)
'may': OUTPUT 31
entered a month.'
'july': OUTPUT 31
'june': OUTPUT 30
'april': OUTPUT 30
'march': OUTPUT 31
'august': OUTPUT 31
START
'december': OUTPUT 31
'november': OUTPUT 30
'february': OUTPUT 28
'september': OUTPUT 30
A pseudocode and flowchart algorithm:
INPUT
LOWER(month)
STOP
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b A Python solution:
month = input('Enter a month: ').lower()
if month == 'january':
print(31)
elif month == 'february':
print(28)
elif month == 'march':
print(31)
elif month == 'april':
print(30)
elif month == 'may':
print(31)
elif month == 'june':
print(30)
elif month == 'july':
print(31)
elif month == 'august':
print(31)
elif month == 'september':
print(30)
elif month == 'october':
print(31)
elif month == 'november':
print(30)
elif month == 'december':
print(31)
else:
print('You have not entered a month.')
A GUI application will have the same logic as the text-based solution given. There are two ways of
obtaining the month data from users in a GUI version of this application:
ii Use a drop-down menu – which is the better solution as the user cannot enter any
unexpected data.
28
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
IF Year MOD 4 = 0
THEN
IF Year MOD 100 = 0 INPUT
THEN year
IF Year MOD 400 = 0
THEN
OUTPUT "Leap Year"
ELSE
OUTPUT "Normal Year" FALSE
year MOD 4 OUTPUT
ENDIF
=0 'Normal year'
ELSE
OUTPUT "Leap Year"
ENDIF TRUE
ELSE
OUTPUT "Normal Year"
ENDIF FALSE
year MOD 100 OUTPUT
=0 'Leap year'
TRUE
FALSE
year MOD 400 OUTPUT
=0 'Normal year'
TRUE
OUTPUT
'Leap year'
b A Python solution:
year = int(input(
'In what year
were you STOP
born?'))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
p
rint('The year is a leap year and has 366 days')
else:
p
rint('The year is not a leap year and has 365 days')
else:
p
rint('The year is a leap year and has 366 days')
else:
print('The year is not a leap year and has 365 days')
29
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Challenge tasks
7.1 Even though there is no ELSE in the pseudocode algorithm, the consequence of a False answer to
the IF clause is that the program carries on:
START
discount ← 0.5
INPUT
ticket_price
child
TRUE ticket_price ←
child = y
ticket_price * discount
FALSE
OUTPUT
ticket_price
STOP
30
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
7.2 As the logic does not change, below is one example of the Python code for a GUI application.
The logic for the other two can be taken from the previous tasks.
from tkinter import *
def is_factor():
number1 = int(number1_textbox.get())
number2 = int(number2_textbox.get())
if number1 % number2 == 0:
label_ans.config(text='Factor')
else:
label_ans.config(text='Not a Factor')
def clear():
number1_textbox.delete(0, END)
number2_textbox.delete(0, END)
label_ans.config(text='')
31
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
7.3 a An if ... elif ... else construct is not as efficient as a CASE statement because
all of the conditions prior to the one that returns True have to be tested. The rest are then
skipped. This makes it just as efficient as a nested if solution. CASE statements are more
efficient than this because they jump straight to the condition that returns True. This is
because they do not actually run any tests. The separate cases are in fact indexed locations
in memory.
b CASE statements are limited to evaluating the output from a single variable. An if ...
elif ... else construct is more flexible because it can have different test conditions at
each new elif clause.
End-of-chapter tasks
1 a A pseudocode and flowchart algorithm:
INPUT number1, number2, number3
32
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INPUT
number1
number2
number3
number1 = number2
OR TRUE
number1 = number3 OUTPUT
OR 'Error: match'
number2 = number3
TRUE
number2 > number3 OUTPUT
number2
OUTPUT STOP
number3
33
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
34
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
IF destination = 'Edinburgh'
THEN
IF ticket_class = 'b'
THEN
IF return_ticket = 'y'
THEN
cost '£178'
ELSE
cost '£87'
ENDIF
ELSE // economy
IF return_ticket = 'y'
THEN
IF meal = 'y'
THEN
cost '£70'
ELSE
cost '£52'
ENDIF
ELSE // single
IF meal = 'y'
THEN
cost '£44'
ELSE
cost '£32'
ENDIF
ENDIF
ENDIF
ELSE // Going to Cardiff
IF ticket_class = 'b'
THEN
IF return_ticket = 'y
THEN
cost '£138'
ELSE
cost '£72'
ENDIF
ELSE // economy
IF return_ticket = 'y'
THEN
IF meal = 'y'
THEN
cost '£68'
35
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
ELSE
cost '£50'
ENDIF
ELSE // single
IF meal = 'y'
THEN
cost '£48'
ELSE
cost '£36'
ENDIF
ENDIF
ENDIF
ENDIF
OUTPUT cost
36
37
b
START
cost ← '£68' cost ← '£50' cost ← '£48' cost ← '£36'
INPUT
destination
ticket_class TRUE FALSE TRUE FALSE
return_ticket meal = 'y' meal = 'y'
A text-based solution:
meal
TRUE
FALSE FALSE
destination = 'Edinburgh' return_ticket = 'y'
cost ← '£87'
FALSE TRUE
cost ← '£138'
cost ← '£178' FALSE
return_ticket = 'y'
STOP
cost ← '£70' cost ← '£52' cost ← '£44' cost ← '£32'
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
if destination == 'Edinburgh':
if ticket_class == 'b':
if return_ticket == 'y':
cost = '£178'
else:
cost = '£87'
else: # economy
if return_ticket == 'y':
if meal == 'y':
cost = '£70'
else:
cost = '£52'
else: # single
if meal == 'y':
cost = '£44'
else:
cost = '£32'
else: # Going to Cardiff
if ticket_class == 'b':
if return_ticket == 'y':
cost = '£138'
else:
cost = '£72'
else: # economy
if return_ticket == 'y':
if meal == 'y':
cost = '£68'
else:
cost = '£50'
else: # single
if meal == 'y':
cost = '£48'
else:
cost = '£36'
print(cost)
c A GUI solution will have the same logic as the above solution but a relatively simple
interface. It will have one output in either a label or a textbox widget and four places for user
input. To ensure no errors in inputs, this GUI could use four sets of radio buttons.
An equally good solution would be four drop-down menus.
38
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Chapter 8: Iteration
Practice tasks
8.1 from turtle import *
for _ in range(6):
forward(100)
left(60)
for _ in range(6):
for _ in range(4):
forward(100)
left(90)
left(60)
FOR i 1 TO number
OUTPUT i*i
NEXT
START
INPUT
number
i←1
TRUE
i > number
i←i+1 FALSE
OUTPUT
i*i
STOP
39
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b A text-based solution:
number = int(input('Input an integer: '))
FOR i 1 TO num
bit_values bit_values + STRING(bit_value) + ', '
bit_value bit_value * 2
NEXT
START
bit_values ← ''
bit_value ← 1
INPUT
num
OUTPUT
TRUE
i > number bit_values with ', '
removed from end
i←i+1 FALSE
b A text-based solution:
bit_values = ''
num = int(input('Input an integer: '))
bit_value = 1
40
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
for _ in range(num):
bit_values = bit_values + str(bit_value) + ', '
bit_value = bit_value * 2
print(bit_values)
START
sentence ← ''
INPUT
word
FALSE OUTPUT
word != 'end'
sentence
TRUE
INPUT
STOP
word
b A text-based solution:
sentence = ''
print(sentence)
c Student testing
41
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
count 1
WHILE num != -1 AND count < 20 DO
INPUT num
total total + num
count count + 1
ENDWHILE
START
INPUT
num
total ← num
count ← 1
num != –1 FALSE
AND average ← total / count
count < 20
TRUE
INPUT OUTPUT
num average
42
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b A text-based solution:
num = int(input('Enter an integer: '))
total = num
count = 1
while num != -1 and count < 20:
num = int(input('Enter an integer: '))
total = total + num
count = count + 1
START
INPUT
password1
password2
OUTPUT STOP
'Error!'
password1 = password2
FALSE TRUE OUTPUT
AND
LENGTH(password1) > 10 'Password accepted'
43
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b A text-based solution:
print('Password accepted')
It is interesting to compare the above solution with a normal while loop program:
password1 = input('Input your password: ')
password2 = input('Input your password again: ')
print('Password accepted')
Both solutions involve repeated code although if we were not trying to implement the pseudocode so
literally the first version could actually be written:
while True:
password1 = input('Input your password: ')
password2 = input('Input your password again: ')
if password1 != password2 or len(password1) < 11:
print('Error!')
else:
break
print('Password accepted')
print(total)
44
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
while True:
number = int(input('Input a number: '))
total = total + number
if number == -1:
break
total = total + 1
print(total)
c Student testing
Challenge task
8.1 #nonsense_sentences_gui.py
from tkinter import *
sentence = ''
def submit_word():
global sentence
word = my_text_entry_box.get()
if word != 'end':
sentence = sentence + word + ' '
my_text_entry_box.delete(0, END)
else:
output_label.config(text=sentence)
# Add GUI
# Create the main tkinter window
window = Tk()
window.title('Nonsense Sentences')
# Add widgets
frame1 = Frame(window, height=1, width=45)
frame1.grid(row=0, column=0)
45
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
label2 = Label(
window, width=45, height=2, text='\nNonsense sentence:',
anchor="w")
label2.grid(row=1, column=0)
output_label = Label(
window, width=45, height=1, text='', anchor="w",
fg='blue')
output_label.grid(row=2, column=0)
The loop is used to total a series of inputs until a negative value is input. The input value must be
checked before the loop runs to avoid including the negative value in the total. The WHILE
loop would be most appropriate as it checks the condition before the loop runs.
INPUT Value
WHILE Value >= 0
Total Total + Value
INPUT Value
ENDWHILE
2 REPEAT...UNTIL
The process requires that a total is maintained of the values input. There will always be at least
one input in this process, even if that input itself is large enough to stop the process and halt any
other inputs. Checking at the end of each input would be most appropriate.
REPEAT
INPUT Value
Total Total + Value
UNTIL Total > 1000
It would be important to check the username and password before allowing access to the system.
The WHILE loop would check that the values input matched system records before allowing
access. If the first input failed, an error message could be generated including a prompt to
try again.
INPUT Username, Password
WHILE Username != SystemUserName AND Password != SystemPassword
OUTPUT 'Access Rejected, re-enter Username and password'
INPUT Username and Password
ENDWHILE
// Run System Access Code
46
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
The REPEAT...UNTIL could also be used to achieve a similar result, but would require the use of an
IF statement to include the error message.
REPEAT
INPUT Username and Password
IF Username != SystemUserName OR Password != SystemPassword
THEN
OUTPUT 'Access Rejected, re-enter Username and password'
ENDIF
UNTIL Username = SystemUserName AND Password = SystemPassword
// Run System Access Code
End-of-chapter tasks
1 a Count-controlled FOR loop.
The user will need to input 25 scores. As the number of iterations is known, a count-controlled loop
would be appropriate.
The number of recordings required is unknown. A condition-controlled loop set to stop when the input
value is 20 would be appropriate.
There are 200 runners so it could be expected that 200 values will need to be input. Using this logic,
a count controlled FOR loop would be appropriate. However, what would happen if a runner fails
to complete the race? Is a time recorded for them? Using a FOR loop would force the input of 200
values. It might be more appropriate to use a condition-controlled loop. The condition could be set so
a negative number would end the input sequence. This would allow the input of times only for those
runners who complete the marathon.
Both methods could be appropriate and the task would need to be better defined before a final decision
could be made.
It is unlikely that the cinema will know how many people are going to watch the film. The number of
ages being input into the system will also be unknown. A condition-controlled loop would seem to be
the most appropriate as the input could be ended when the last ticket is bought. The condition could be
set so a negative number would end the input sequence. As it is not possible to have a negative age this
would seem an appropriate condition. It might also be appropriate to end the input when tickets for all
available seats have been sold. This could be a second condition.
47
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
num = int(input(
'Enter an
integer: '))
print('The factors of', num, 'are:') counter ← 1
counter ←
FALSE
counter + 1
TRUE
OUTPUT
counter
3
from turtle import *
for _ in range(sides):
forward(100)
left(angle)
48
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INPUT
num1
num2
OUTPUT
'The factors of ' + num1 +
'and ' + num2 + 'are: '
counter ← FALSE
counter + 1
TRUE
OUTPUT
counter
A pseudocode algorithm:
INPUT num1
INPUT num2
//Find largest:
largest num1
IF num2 > num1
THEN
largest num2
ENDIF
49
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
OUTPUT series
50
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INPUT
num
STOP
a←0
b←1
series ← '0, 1, ' OUTPUT
series
counter ← FALSE
counter + 1
temp ← a
a←b
b ← a + temp
series ← series + b + ', '
b A text-based solution:
num = int(input('Enter an integer: '))
a = 0
b = 1
series = '0, 1, '
51
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Average pages in
a library book
52
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
total ← 0
count ← 0
INPUT
num_pages
FALSE OUTPUT
num_pages
>0 average
count ←
count + 1 TRUE
INPUT
num_pages STOP
count 0
WHILE num_pages > 0 DO
total total + num_pages
INPUT num_pages
count count + 1
ENDWHILE
53
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
count = 0
while num_pages > 0:
total = total + num_pages
num_pages = int(input('Total pages: '))
count = count + 1
Challenge tasks
9.1 The design shown below assumes that when a weather station sends in their monthly figures that this is all
the data that they have. If the data for some of the days is missing this is because no measurements were
taken. The proposed system will estimate values for the missing days.
Collect
rainfall data
(The circles in two of the boxes indicate that they are alternatives.)
54
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
total ← 0
count ← 0
INPUT
daily_rainfall
FALSE
daily_rainfall OUTPUT
>= 0 total
count ←
count +1 TRUE
INPUT
daily_rainfall STOP
A Python solution:
total = 0
55
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
End-of-chapter tasks
1 total 0
INPUT monthly_rainfall
count 0
WHILE monthly_rainfall >= 0 DO
total total + monthly_rainfall
INPUT monthly_rainfall
count = count + 1
ENDWHILE
count = 0
while monthly_rainfall >= 0:
total = total + monthly_rainfall
monthly_rainfall = float(input('Rainfall to 0.1mm: '))
count = count + 1
average = total / count
56
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
score ← 0
hit ← 0
INPUT
hit
FALSE
OUTPUT
hit != – 1
score
TRUE
INPUT
hit
57
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
score = 0
def hit():
global score
score = score + 1
label_ans.config(text='')
def finish():
global score
label_ans.config(text=score)
score = 0
58
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Draw a house
START START
START
draw_rectangle draw_triangle
CALL
draw_rectangle(300, 200) parameter: height parameters: x1, y1
draw_triangle(0, 200, 300, 200, 150, 300) parameter: width parameters: x2, y2
parameters: x3, y3
goto(40, 70)
pendown
left(90)
forward(width) goto(x1, y1)
left(90) pendown
forward(height) goto(x2, y2)
CALL left(90) goto(x3, y3)
draw_rectangle(100, 80) forward(width) goto(x1, y1)
left(90) penup
forward(height)
penup
goto(180, 0)
left(90)
STOP
draw_triangle
STOP
CALL draw_rectangle
draw_rectangle(80, 150)
hide turtle()
STOP
59
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
PROCEDURE draw_triangle(x1,y1,x2,y2,x3,y3)
goto(x1,y1)
pendown
goto(x2,y2)
goto(x3,y3)
goto(x1,y1)
penup
ENDPROCEDURE
// Draw House
draw_rectangle(300,200)
draw_triangle(0,200,300,200,150,300)
goto(40,70)
left(90)
draw_rectangle(100,80)
goto(180,0)
left(90)
draw_rectangle(80,150)
hideturtle()
60
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
def draw_triangle(x1,y1,x2,y2,x3,y3):
t.goto(x1,y1)
t.pendown()
t.goto(x2,y2)
t.goto(x3,y3)
t.goto(x1,y1)
t.penup()
# Draw House
draw_rectangle(300,200)
draw_triangle(0,200,300,200,150,300)
t.goto(40,70)
t.left(90)
draw_rectangle(100,80)
t.goto(180,0)
t.left(90)
draw_rectangle(80,150)
t.hideturtle()
def input_data():
data_item = int(input('Enter an integer: '))
index = int(input('Enter an index from 0 to 3: '))
task[index] = data_item
def output_data():
index = int(input('Enter an index from 0 to 3: '))
print(task[index])
choice = '0'
while choice != '3':
choice = input('''
Menu:
1. Input data
2. Output data
3. Finish
Choose 1, 2 or 3: ''')
if choice == '3':
61
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
if choice == '1':
input_data()
else:
output_data()
10.2 W
hen the program ends the values in the arrays are lost. This means that every time the program
is started the values have to be re-entered.
START
INPUT
number
OUTPUT
names[number–1]
STOP
62
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b A Python implementation:
names = ['Albert', 'Beck', 'Caro', 'Dimpna', 'Eli', 'Filiz']
number = int(input('Enter a number between from 1 to 6: '))
print(names[number-1])
10.4 a A flowchart for the system with the array numbered from 1 to 6:
START
found ← FALSE
i←1
INPUT
name
FALSE TRUE
i←i+1
OUTPUT
FALSE name = STOP
'No match.'
names[i]
TRUE
OUTPUT
'Name found.'
found ← TRUE
63
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
INPUT name
// Perform search
FOR i 1 TO 6
IF name = names[i]
THEN
OUTPUT 'Name found.'
found = TRUE
ENDIF
NEXT
IF found = FALSE
THEN
OUTPUT 'No match.'
ENDIF
# Perform search
for i in range(6):
if name == names[i]:
print('Name found.')
found = True
if found == False:
print('No match.')
64
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
found ← FALSE
i←1
INPUT
name
FALSE TRUE
i←i+1
OUTPUT
FALSE name = STOP
'No match.'
names[i]
TRUE
OUTPUT
'Name found at' + i
found ← TRUE
INPUT name
// Perform search
FOR i 1 TO 6
IF name = names[i]
65
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
THEN
OUTPUT 'Name found at location: ' + i
found = TRUE
ENDIF
NEXT
IF found = FALSE
THEN
OUTPUT 'No match found.'
ENDIF
A Python implementation:
names = ['Albert', 'Beck', 'Caro', 'Beck', 'Caro', 'Beck']
found = False
# Perform search
for i in range(6):
if name == names[i]:
print('Name found at location: ', i)
found = True
if found == False:
print('No match found.')
found = False
user_letter = input('Enter the character to search for: ')
counter = 0
# Perform search of letters
while counter < len(letters) and found == False:
if user_letter == letters[counter]:
found = True
counter = counter + 1
if found == True:
print('Match found.')
else:
print('No match.')
# Call function
search()
66
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
FOR i 0 TO 3
IF search_ID = BabyID[i]
THEN
OUTPUT gender[i], weight[i], blood_group[i]
ENDIF
NEXT
b A Python implementation:
# Initialise arrays:
BabyID = ['B2003', 'B2004', 'B2005']
gender = ['Male', 'Female', 'Female']
weight = [3.5, 3.34, 3.62]
blood_group = ['O Neg', 'A Pos', 'O Pos']
for i in range(0,3):
if search_ID == BabyID[i]:
p
rint(gender[i] + ' ' + str(weight[i]) + 'kg ' + blood_group[i])
10.8 a–b
# In arrays the weights have to be
# stored in strings but with Python lists
# this is unnecessary.
# Initialise 2D array:
baby_data = [['B2003', 'Male', '3.5' , 'O Neg'],
['B2004', 'Female', '3.34', 'A Pos'],
['B2005', 'Female', '3.62', 'O Pos']]
for i in range(0,3):
if search_ID == baby_data[i][0]:
print(baby_data[i][1] + ' ' + baby_data[i][2]
+ 'kg ' + baby_data[i][3])
67
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Challenge tasks
10.1 A text-based Python solution:
# Initialise arrays:
BabyID = ['B2003', 'B2004', 'B2005']
gender = ['Male', 'Female', 'Female']
weight = [3.5, 3.34, 3.62]
blood_group = ['O Neg', 'A Pos', 'O Pos']
10.2 #
Initialise 2D array:
baby_data = [['B2003', 'B2004', 'B2005'],
['Male', 'Female', 'Female'],
['3.5', '3.34', '3.62'],
['O Neg', 'A Pos', 'O Pos']]
68
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Pass 1:
Pass 2:
Pass 3:
End-of-chapter tasks
1 a A pseudocode algorithm:
numbers [17, 103, 36, 42, 85, 3, 64, 98, 55, 11]
total 0
largest 0
smallest 1000000
PROCEDURE input_data()
INPUT data_item
INPUT index // From 0 to LENGTH(numbers)-1
numbers[index] data_item
ENDPROCEDURE
PROCEDURE output_data():
global total
global largest
global smallest
FOR i 0 TO LENGTH(numbers)-1
total total + numbers[i]
IF numbers[i] > largest
THEN
largest numbers[i]
ENDIF
IF numbers[i] < smallest
THEN
smallest numbers[i]
ENDIF
NEXT
// Main program
choice '0'
WHILE choice != '3' DO
choice INPUT '1', '2' or '3'
69
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
IF choice = '3'
THEN
OUTPUT 'Thanks for using this application.'
ELSE
WHILE (choice != '1' and choice != '2') DO
choice INPUT INPUT '1', '2' or '3'
ENDWHILE
IF choice = '1'
THEN
input_data()
ELSE
output_data()
ENDIF
input('\nPress any key to continue.')
ENDWHILE
ENDWHILE
b Since the loop has to loop through every number to find the total of them, we cannot
optimise it any further.
c A Python implementation:
numbers = [17, 103, 36, 42, 85, 3, 64, 98, 55, 11]
total = 0
largest = 0
smallest = 1000000
def input_data():
data_item = int(input('Enter an integer: '))
index = int(input(
'Enter an index from 0 to ' +
str(len(numbers)-1) + ': '))
numbers[index] = data_item
def output_data():
global total
global largest
global smallest
for i in range(len(numbers)):
total = total + numbers[i]
if numbers[i] > largest:
largest = numbers[i]
if numbers[i] < smallest:
smallest = numbers[i]
70
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
# Main program
choice = '0'
while choice != '3':
choice = input('''
Menu:
1. Input data
2. Output data
3. Finish
Choose 1, 2 or 3: ''')
if choice == '3':
print('\nThanks for using this application.')
else:
while (choice != '1' and choice != '2'):
choice = input('Enter 1, 2 or 3: ')
if choice == '1':
input_data()
else:
output_data()
2 a A turtle answer:
# rainbow.py
from turtle import *
pensize(50)
line_length = 20
colours = ['Red', 'Orange', 'Yellow', 'Blue', 'Green', 'Indigo', 'Violet']
for i in range(7):
pencolor(colours[i])
forward(line_length)
right(72)
line_length = line_length + 15
b A turtle answer:
# rainbow.py
from turtle import *
pensize(50)
line_length = 20
colours = ['Red', 'Orange', 'Yellow', 'Blue', 'Green', 'Indigo', 'Violet']
for i in range(14):
if i < 7:
pencolor(colours[i])
forward(line_length)
71
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
right(72)
line_length = line_length + 15
else:
pencolor(colours[i-7])
forward(line_length)
right(72)
line_length = line_length + 15
c A turtle answer:
# rainbow.py
from turtle import *
import random
pensize(50)
line_length = 20
colours = ['Red', 'Orange', 'Yellow', 'Blue', 'Green', 'Indigo', 'Violet']
for i in range(10):
pencolor(random.choice(colours))
forward(line_length)
right(72)
line_length = line_length + 15
3 a A pseudocode algorithm:
nums[0:5] OF Integer
// Gather the data and enter it in the array:
FOR i 0 TO 5
INPUT num
nums[i] num
NEXT
IF nums[0] = nums[5] AND nums[1] = nums[4] AND nums[2] = nums[3]
THEN
OUTPUT 'Palindrome'
ELSE
OUTPUT 'Nothing special'
ENDIF
b A Python implementation:
nums = [None]*6
# Gather the data and enter it in the array:
for i in range(6):
num = int(input('Enter a digit: '))
nums[i] = num
if nums[0] == nums[5] and nums[1] == nums[4] and nums[2] == nums[3]:
print('Palindrome')
else:
print('Nothing special')
72
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
4 Here is the pseudocode for three functions that could be used in your program. They then just
need to be called by a menu system. An example is shown in the Python code below.
// Initialise arrays:
Type ['Cat', 'Dog', 'Dog', 'Parrot']
Colour ['White', 'Black & White', 'Grey', 'Blue & Red']
Min_age [5, 12, 1, 8]
Breed ['Persian', 'Husky', 'Poodle', 'Macaw']
length len(Type)
PROCEDURE get_data()
INPUT pet_type
FOR i 0 TO length - 1
IF pet_type = Type[i]
THEN
OUTPUT Colour[i], Breed[i], Min_age[i]
ENDIF
NEXT
ENDPROCEDURE
PROCEDURE get_suitable()
INPUT age
FOR i 0 TO length - 1
IF age >= Min_age[i]
THEN
OUTPUT Colour[i], Breed[i], Type[i]
ENDIF
NEXT
ENDPROCEDURE
PROCEDURE get_suitable_advanced()
INPUT pet_type
INPUT age
FOR i 0 TO length - 1
IF pet_type = Type[i] and age >= Min_age[i]
THEN
OUTPUT Colour[i], Breed[i], Type[i]
ENDIF
NEXT
ENDPROCEDURE
73
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
def get_data():
pet_type = input('Animal type: ')
for i in range(length):
if pet_type == Type[i]:
print(Colour[i], Breed[i], 'suitable for children over',
Min_age[i])
def get_suitable():
age = int(input('Youngest pet owner age (if adult enter 18): '))
for i in range(length):
if age >= Min_age[i]:
print(Colour[i], Breed[i], Type[i])
def get_suitable_advanced():
pet_type = input('Animal type: ')
age = int(input('Youngest pet owner age (if adult enter 18): '))
for i in range(length):
if pet_type == Type[i] and age >= Min_age[i]:
print(Colour[i], Breed[i], Type[i])
# Main program
choice = '0'
while choice != '4':
choice = input('''
Menu:
1. Find data about an animal type
2. Find pets based on owner age
3. Find pets based on owner age and pet type
4. Finish
Choose 1, 2, 3 or 4: ''')
if choice == '4':
print('\nThanks for using this application.')
break
else:
while (choice != '1' and choice != '2' and choice != '3'):
choice = input('Enter 1, 2, 3 or 4: ')
if choice == '1':
get_data()
elif choice == '2':
get_suitable()
else:
get_suitable_advanced()
74
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
5 Here is the pseudocode for the three functions that could be used in your program.
// Initialise 2D array:
pets [['Cat', 'Dog', 'Dog', 'Parrot'],
['White', 'B&W', 'Grey', 'Blue & Red'],
['5', '12', '1', '8'],
['Persian', 'Husky', 'Poodle', 'Macaw']]
length len(pets[0])
PROCEDURE get_data()
INPUT pet_type
FOR i 0 TO length - 1
IF pet_type = pets[0][i]
THEN
OUTPUT pets[1][i], pets[3][i], pets[2][i]
ENDIF
NEXT
ENDPROCEDURE
PROCEDURE get_suitable()
INPUT age
FOR i 0 TO length - 1
IF age >= pets[2][i]
THEN
OUTPUT pets[1][i], pets[3][i], pets[0][i]
ENDIF
NEXT
ENDPROCEDURE
PROCEDURE get_suitable_advanced()
INPUT pet_type
INPUT age
FOR i 0 TO length - 1
IF pet_type = pets[0][i] and age >= pets[2][i]
THEN
OUTPUT pets[1][i], pets[3][i], pets[0][i]
ENDIF
NEXT
ENDPROCEDURE
length = len(pets[0])
75
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
def get_data():
pet_type = input('Animal type: ')
for i in range(length):
if pet_type == pets[0][i]:
p
rint(pets[1][i], pets[3][i], 'suitable for children over',
pets[2][i])
def get_suitable():
age = int(input('Youngest pet owner age (if adult enter 18): '))
for i in range(length):
if age >= int(pets[2][i]):
print(pets[1][i], pets[3][i], pets[0][i])
def get_suitable_advanced():
pet_type = input('Animal type: ')
age = int(input('Youngest pet owner age (if adult enter 18): '))
for i in range(length):
if pet_type == pets[0][i] and age >= int(pets[2][i]):
print(pets[1][i], pets[3][i], pets[0][i])
b A Python implementation:
last_name = input('Enter your lastname:')
TRUE OUTPUT
while last_name == '': last_name
'Error.'
print('Error.') =''
last_name = input('Enter your lastname:')
FALSE
# program continues
Continue with
program
76
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INPUT
month
month = ''
OR TRUE OUTPUT
month > 12
'Error.'
OR
month < 1
FALSE
Continue with
program
A pseudocode implementation:
INPUT month
// program continues
b A Python implementation:
The while loop tests for no entry as well as the range 1 to 12. It is therefore best not to cast
the input into an integer until the conditions for the while loop have been met, otherwise
errors will be thrown when an empty is string is entered as input.
month = input('Month? [Enter 1 to 12]: ')
# program continues
77
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
// Program continues
INPUT month
# program continues
INPUT
11.5 a A flowchart algorithm: date
A pseudocode implementation:
INPUT date
Continue with
program
78
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b A Python implementation:
from datetime import datetime
def validate_date(d):
while True:
try:
return datetime.strptime
(d, '%Y/%m/%d')
except:
d = input('Date must be in the format yyyy/mm/dd: ')
# Program continues
79
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Challenge tasks
11.1 a A flowchart algorithm:
START
INPUT
first_name
first_name =''
OR TRUE OUTPUT
just_letters(first_name) 'Error.'
= FALSE
FALSE
Continue with
program
A pseudocode implementation:
FUNCTION just_letters(word)
letters ['a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z']
80
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
RETURN FALSE
ENDIF
ENDFUNCTION
INPUT first_name
81
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
just_letters(word)
letters ← ['a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z']
chars ← ARRAY(LOWER(word))
RETURN
correct_counter ← 0 TRUE
i←0
j←0
TRUE
i ← i +1 FALSE
FALSE
TRUE j= RETURN
LENGTH(letters) FALSE
FALSE
j ← j +1
chars[i] FALSE
=
letters[j]
TRUE
correct_counter ←
counter_correct + 1
b A Python implementation:
def just_letters(word):
letters = ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z']
82
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
# program continues
83
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
is_a_day(d)
i←0
TRUE
RETURN
i=7
FALSE
FALSE
i ← i +1 STOP
is_a_day(d)
84
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
A pseudocode implementation:
FUNCTION is_a_day(d)
days ['monday', 'tuesday', 'wednesday', 'thursday',
'friday', 'saturday', 'sunday']
FOR i 0 TO 6
IF LOWER(d) = days[i]
THEN
RETURN TRUE
ENDIF
RETURN FALSE
ENDFUNCTION
INPUT day
// program continues
b Below is a Python implementation that iterates through an array to check that the input matches one
of the items in it. There are a number of ways of doing this. By doing it this way there is no need to
test for the presence of an empty string because that does not exist in the array.
def is_a_day(d):
days = ['monday', 'tuesday', 'wednesday', 'thursday',
'friday', 'saturday', 'sunday']
for i in range(7):
if d.lower() == days[i]:
return True
return False
# program continues
85
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Of course using Python’s list tools, this could have been achieved without iterating through the list like this:
days = ['monday', 'tuesday', 'wednesday', 'thursday',
'friday', 'saturday', 'sunday']
# program continues
START
INPUT
p
LENGTH(p) < 6
OR
TRUE OUTPUT
contains_letter(p) = FALSE
OR 'Error.'
contains_number(p)
= FALSE
FALSE
Continue with
program
86
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
contains_letter(password)
letters ← ['a','b','c','d','e','f','g','h',
'i','j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z']
pw ← ARRAY(password)
i←0
j←0
TRUE RETURN
i = LENGTH(pw)
FALSE
i ← i +1 FALSE
TRUE
j = LENGTH(letters)
FALSE
j ← j +1
LOWER(pw[i]) FALSE
=
letters[j]
TRUE
RETURN STOP
TRUE contains_letter(password)
87
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
contains_number(password)
numbers ← ['0','1','2','3','4','5','6','7','8','9']
pw ← ARRAY(password)
i←0
j←0
TRUE RETURN
i = LENGTH(pw)
FALSE
i ← i +1 FALSE
TRUE j=
LENGTH(numbers)
FALSE
j ← j +1
pw[i] FALSE
=
numbers[j]
TRUE
RETURN STOP
TRUE contains_number(password)
88
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
A pseudocode implementation:
FUNCTION contains_letter(password)
letters ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z']
// Create an array from letters in password
pw ARRAY(password)
FOR i 0 TO LENGTH(pw)-1
FOR j 0 TO LENGTH(letters)-1
IF LOWER(pw[i]) = letters[j]
THEN
RETURN TRUE
ENDIF
NEXT
NEXT
RETURN FALSE
ENDFUNCTION
FUNCTION contains_number(password):
numbers ['0','1','2','3','4','5','6','7','8','9']
pw ARRAY(password)
FOR i 0 TO LENGTH(pw)-1
FOR j TO LENGTH(numbers)-1
IF pw[i] = numbers[j]
THEN
RETURN TRUE
ENDIF
NEXT
NEXT
RETURN FALSE
ENDFUNCTION
INPUT p
// Program continues
b A Python implementation:
def contains_letter(password):
letters = ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z']
89
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
pw = list(password)
for i in range(len(pw)):
for j in range(len(letters)):
if pw[i].lower() == letters[j]:
return True
return False
def contains_number(password):
numbers = ['0','1','2','3','4','5','6','7','8','9']
pw = list(password)
for i in range(len(pw)):
for j in range(len(numbers)):
if pw[i] == numbers[j]:
return True
return False
# Program continues
The above program can be made more efficient by doing both tests in one function and inside one set
of nested loops rather than separately. This will make the code harder to read and debug. The function
will also be less flexible because then they cannot be used elsewhere in the program separately, should
this be needed. Again there is a simpler way of writing these two functions in Python:
def contains_letter(password):
letters = 'abcdefghijklmnopqrstuvwxyz'
for i in range(len(password)):
if password[i].lower() in letters:
return True
break
return False
def contains_number(password):
numbers = '1234567890'
for i in range(len(password)):
if password[i] in numbers:
return True
break
return False
90
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INPUT
day
FALSE
Continue with
program
A pseudocode implementation:
INPUT day
// program continues
b A Python implementation:
day = input('Enter day of month: ')
while True:
try:
while int(day) > 31 or int(day) <1:
day = input('Enter a number from 1 to 31: ')
break
except:
day = input('Not an integer. Please enter month as an integer: ')
# program continues
91
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
INPUT
fn
fn = ''
OR
just_letters(fn) = FALSE TRUE OUTPUT
OR 'Error.'
begins_capital(fn)
= FALSE
FALSE
Continue with
program
START
begins_capital(word)
STOP
begins_capital(word)
92
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
just_letters(word)
letters ← ['a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x','y','z',"'",'-']
chars ← ARRAY(LOWER(word)
RETURN
correct_counter ← 0 TRUE
i←0
j←0
TRUE
i ← i +1 FALSE
FALSE
j=
TRUE RETURN
LENGTH(letters)
FALSE
FALSE
j ← j +1
chars[i] FALSE
=
letters[j]
TRUE
correct_counter ←
counter_correct + 1
93
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
FUNCTION begins_capital(word)
IF word[0] is uppercase
THEN
RETURN TRUE
ELSE
RETURN FALSE
ENDIF
ENDFUNCTION
INPUT fn
// program continues
94
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
def begins_capital(word):
if word[0].isupper():
return True
else:
return False
while fn == '' o
r just_letters(fn) == False
or begins_capital(fn) == False:
print('Error.')
fn= input('Enter your first name: ')
# program continues
As this is an Extension Challenge task, we can look a little more at style. Look at this bit of code:
if correct_counter == len(chars):
return True
else:
return False
This follows the IF...ELSE structure we have learnt in Chapter 7 but we can write this in a much
shorter (and more correct) way. The double equals symbol is a Boolean operator so it is already
returning True or False to the IF clause. This means that we can replace all the above code with:
return correct_counter == len(chars)
95
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
def begins_capital(word):
return word[0].isupper()
# Program continues
96
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
STOP
A pseudocode implementation:
odds 3 * (barcode[0] + barcode[2] + barcode[4] + barcode[6])
evens (barcode[1] + barcode[3] + barcode[5])
checkdigit (odds + evens) % 10
IF checkdigit = barcode[7]
THEN
OUTPUT 'valid'
ELSE
OUTPUT 'invalid'
ENDIF
b A Python implementation:
# test data
barcode = [3, 4, 7, 8, 6, 6, 2, 2]
# main program
odds = 3 * (barcode[0] + barcode[2] + barcode[4] + barcode[6])
evens = (barcode[1] + barcode[3] + barcode[5])
checkdigit = (odds + evens) % 10
if checkdigit == barcode[7]:
print('valid')
else:
print('invalid')
97
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
End-of-chapter tasks
1 A Python text-based solution:
def valid_user(u, p):
# validate username
letters = ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z','-']
# validate password
if len(p) != 7:
return False
if p[0] != 'P':
return False
if int(p[1:7]) > 999999:
return False
if int(p[1:7]) < 100000:
return False
98
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
# test function:
username = input('Username: ')
password = input('Password: ')
print(valid_user(username, password))
2 a A flowchart algorithm:
START
INPUT
username
password
valid_user(username, TRUE
password) = True
FALSE
valid_user(username, TRUE
password) = TRUE
FALSE
OUTPUT
'Locked Out.'
99
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START STOP
valid_user(u, p) valid_user(u, p)
letters ← ['a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','o','p','q','r','s','t','u','v','w','x','y','z','-'] FALSE
correct_counter = RETURN
chars ← ARRAY(u) FALSE
LENGTH(chars)
i←0
TRUE
j←0
correct_counter ← 0
FALSE
RETURN
LENGTH(p) FALSE
=7
i= TRUE
LENGTH(chars)
TRUE
i ← i +1 FALSE FALSE
RETURN
(p)[0] = 'P' FALSE
j=
TRUE
LENGTH(letters) TRUE
TRUE
TRUE
RETURN
TRUE
100
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
A pseudocode implementation:
IMPORT sys
FUNCTION valid_user(u, p)
// validate username
letters ['a','b','c','d','e','f','g',
'h','i','j','k','l','m','n',
'o','p','q','r','s','t','u',
'v','w','x','y','z','-']
// validate password
IF LENGTH(p) != 7
THEN
RETURN FALSE
ENDIF
IF p[0] != 'P'
THEN
RETURN FALSE
ENDIF
IF int(p[1:7]) > 999999
THEN
RETURN FALSE
ENDIF
IF int(p[1:7]) < 100000
THEN
RETURN FALSE
ENDIF
101
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
INPUT username
INPUT password
102
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
The output is incorrect as 60 quotient 15 = 4. The error is in the last iteration – the loop
condition should read WHILE x >= y.
12.3 a The aim of the flowchart is to return a5. Use of trace tables with different input values can
help to determine the purpose of unfamiliar programs.
12.4 a The value passed to tins is correctly cast to an Integer as you cannot have a fraction of a tin
of paint. The system makes use of simple division to calculate the number of tins of paint
required; the resultant number is then rounded to an Integer. In some of your test cases, you
should have found that this results in the number of tins being rounded down. In test cases
where rounding area / coverage produces results with the decimal part of the answer being
0.5 or more, this is not a problem. Rounding down, though, will result in not having enough
paint to complete the job.
b To resolve the problem, the number of tins calculated needs to be rounded up. This could be
achieved in pseudocode by using a ROUND UP command. In Python this could be solved
by importing the math library and using the ceil() function:
>>> 4.9 * 0.5
2.45
>>> int(4.9 * 0.5)
2
>>> import math
>>> math.ceil(4.9 * 0.5)
3
103
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
12.5 a
and b Appropriate data types and input validation with boundary data mentioned when
appropriate.
(continued)
104
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
You might be surprised to see the older age being used to test the minimum end of the range check for
date of birth. Remember the older you are the earlier your date of birth.
Challenge tasks
12.1 a x y counter Output Comments
−1 Initialisation values of the variables.
15 5 −1 The new values are input.
x is reduced by y, counter is incremented by 1.
10 5 0 Loop returns to the WHILE condition check.
As x > −1, loop runs.
x is reduced by y, counter is incremented by 1.
5 5 1 Loop returns to the WHILE condition check.
As x > −1, loop runs.
x is reduced by y, counter is incremented by 1.
0 5 2 Loop returns to the WHILE condition check.
As x > −1, loop runs.
(continued)
105
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
106
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b x y w Output Comments
18 6 The new values are input.
18 6 6 w is assigned the value of y.
x is reduced by y, w is increased by y.
12 6 12 Loop returns to the WHILE condition check.
As x > 0, loop runs.
x is reduced by y, w is increased by y.
6 6 18 Loop returns to the WHILE condition check.
As x > 0, loop runs.
x is reduced by y, w is increased by y.
0 6 24 Loop returns to the WHILE condition check.
As x = 0, loop runs.
-6 6 30 As x < 0, loop exits.
30 The value in w is output.
End-of-chapter tasks
1 a Alpha testing – the game has not been completed or distributed at this point.
b Beta testing – the weather app has been completed and is now being distributed to selected
testers before being deployed to the public.
2 a Runtime error
b Syntax error
c Logical error
3 a Runtime errors can be detected by the IDE when the program is run or compiled. The IDE
will display error messages and often highlight the line where the problem occurs. This may
be enough for the programmer to fix the problem straight away. Alternatively, there may be a
need to consult the official language documentation to find out what is the required syntax in
this situation.
b Syntax errors are usually visible before a program is run or compiled in the IDE. “Pretty
text” or “syntax highlighting” is a feature found in all programming IDEs. A programmer
can often spot mistakes by looking out for where this goes wrong. For example, when many
lines of code are green in IDLE this indicates that a speech mark has been missed off the end
of a string. On other occasions the syntax errors may be small but will be highlighted by the
IDE when the programmer tries to run or compile it. An error message will also be given to
indicate what the problem is.
c Logical errors can be found by producing trace tables, running the IDE debugger and
stepping through a program to see what values are held in each variable at each line of the
program; by running tests with boundary, incorrect, and invalid data sets to see whether the
expected output is produced and by alpha and beta testing. Fixing the errors needs careful
thought but is often easier than finding them. Once a fix has been applied another set of tests
will need to be run.
107
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
108
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
5 A Python implementation of the algorithm from the corrected pseudocode in task 4 is shown
here:
large = 0
total = 0
counter = 0
print('Average:', average)
print('Smallest:', small)
print('Largest:', large)
109
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
temp_text ''
FOR i 0 TO 12
temp_text temp_text + STRING(tuesday_array[i]) + ','
NEXT
CLOSE tuesday
b A Python solution:
# tuesday.py
tuesday_list = [4, 4, 8, 10, 14, 17, 19, 20, 20, 19, 17, 16, 14]
temp_text = ''
for i in tuesday_list:
temp_text = temp_text + str(i) + ','
temp_text = temp_text[0:-1]
tuesday.close()
To check this script has done what is expected, open the created tuesday.txt file in a text
editor and see what is in it.
110
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
13.3 ‘Player alias’ could be used as the primary key for this database table. It is the only other field to have a
set of unique values.
13.6 T
here are no variables in database_tool.py that are written to a file or database so everything is reset
after quitting. As you have only learnt how to query a database at the moment (rather than write to
one) the database contents are also unchanged.
13.7 a
SELECT * FROM Book
ORDER BY Year ASC;
b
SELECT Title FROM Book
WHERE Author = 'Orwell'
ORDER BY Title ASC;
c
SELECT Title, Author FROM Book
ORDER BY Year ASC;
d
SELECT Title, Author, Year FROM Book
ORDER BY Author ASC, Title ASC;
e
SELECT Author, Title, Year FROM Book
ORDER BY Year DESC;
f
SELECT Title FROM Book
WHERE Year > 1940 AND Year < 1950
ORDER BY Year ASC;
111
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b
SELECT SUM(Strength) FROM Character
WHERE Sprite = 'Giant';
c
SELECT COUNT(Strength) FROM Character
WHERE Sprite = 'Elf';
b If all went well in part a, the file trees.db should be found in the same folder as
database_tool.py.
Challenge tasks
13.1 # names.py
name = open('name.txt', 'r')
names = name.read().split()
name.close()
13.2 S
ELECT SUM(Speed), SUM(Strength) FROM Character
WHERE Sprite = 'Giant';
112
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
End-of-chapter tasks
1 a A pseudocode solution:
date OPEN birthday.txt
WRITE '25th May 2009' TO date
CLOSE date
b A Python solution:
date = open('birthday.txt', 'w')
date.write('25th May 2009')
date = open('birthday.txt', 'r')
print('I was born on ', date.read())
date.close()
2 a A pseudocode solution:
PROCEDURE update_leaderboard(name)
leader OPEN leader.txt
WRITE name TO leader
CLOSE leader
ENDPROCEDURE
b A Python solution:
def update_leaderboard(name):
leader = open('leader.txt', 'w')
leader.write(name)
leader.close()
# Test
my_name = input('Name: ')
update_leaderboard(my_name)
After running this program and entering your name a file called leader.txt should appear in the same
folder as the Python file.
3 a A pseudocode solution:
PROCEDURE get_leader()
file OPEN leader.txt
leader READ file
OUTPUT "Today's leader is:" + leader
CLOSE file
ENDPROCEDURE
CALL get_leader()
113
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b A Python solution:
def get_leader():
file = open('leader.txt', 'r')
leader = file.read()
print("Today's leader is:", leader)
file.close()
get_leader()
b
SELECT * FROM Character
WHERE Sprite = 'Giant';
b
SELECT COUNT(Title) FROM Book
WHERE Author = 'Orwell';
Chapter 14:
Programming scenario task
End-of-chapter tasks
1 A pseudocode solution:
// Initialise global variables
player1_score 0
player2_score 0
// Game function
FUNCTION play RETURNS INTEGER
score 0
FOR i 1 TO 10
IF INPUT('Guess a number from 1 to 10: ')) = rand_num()
THEN
score score +1
ENDIF
NEXT i
RETURN score
ENDFUNCTION
114
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
// Player 1 turn
OUTPUT 'Player 1, Are you ready?'
player1_score play()
OUTPUT 'You scored', player1_score
// Player 2 turn
OUTPUT 'Player 2, Are you ready?'
player2_score play()
OUTPUT 'You scored', player2_score
// Output results
IF player1_score > player2_score
THEN
OUTPUT 'Player 1 is the winner!'
ELSE
IF player1_score = player2_score
THEN
OUTPUT 'The game is a draw!'
ELSE
OUTPUT 'Player 2 is the winner!'
ENDIF
ENDIF
A Python solution:
from random import *
# Game function
def play():
score = 0
for i in range(10):
i
f int(input('Guess a number from 1 to 10: ')) == randint(1,10):
score = score +1
return score
# Main program
# Player 1 turn
print('\n Player 1, Are you ready?')
player1_score = play()
print('You scored', player1_score)
# Player 2 turn
print('\n Player 2, Are you ready?')
player2_score = play()
print('You scored', player2_score)
115
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
2 A pseudocode solution:
// Program to calculate info from three provided arrays:
// SnackName[], Nutrition[]
SampleSize 5
// Counters
reds 0
oranges 0
greens 0
health_index_total 0
// Loop to complete calculations for each snack
FOR i 0 TO SampleSize-1
mass Nutrition[i][0] + Nutrition[i][2] + Nutrition[i][3]
carb_percent round((Nutrition[i][0] * 100) / mass, 0)
OUTPUT SnackName[i])
OUTPUT 'Percentage carbohydrate by mass:', carb_percent
// Calculate HealthIndex
HealthIndex Nutrition[i][0] + (Nutrition[i][1] * 2) + (
Nutrition[i][3]
* 100)
health_index_total health_index_total + HealthIndex
OUTPUT 'HealthIndex:', ROUND(HealthIndex, 0)
116
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
A Python solution:
# Program to calculate info from three provided arrays:
# SnackName[], Nutrition[]
SampleSize = 5
# Counters
reds = 0
oranges = 0
greens = 0
health_index_total = 0
# Calculate HealthIndex
H
ealthIndex =Nutrition[i][0] + (Nutrition[i][1] * 2) + (
Nutrition[i][3]
* 100)
health_index_total = health_index_total + HealthIndex
print('HealthIndex:', int(round(HealthIndex, 0)))
117
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
3 A pseudocode solution:
FUNCTION format_check(user_id) RETURNS BOOLEAN
IF LENGTH(user_id) != 6
THEN
OUTPUT 'Error: userID is wrong length.'
RETURN FALSE
ENDIF
alphabet ['a','b','c',''d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z']
118
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
IF all_ok = FALSE
THEN
OUTPUT 'No further attempts allowed.'
ELSE
OUTPUT 'CustomerID accepted.'
ENDIF
A Python solution:
def format_check(user_id):
if len(user_id) != 6:
print('Error: userID is wrong length.')
return False
alphabet = 'abcdefghijklmnopqrstuvwxyz'
4 A pseudocode solution:
// Program to calculate info from the provided arrays:
// Members[], Distance[]
number_members 50
overall_distance 0
// Loop to complete calculation for each member
119
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
FOR i 0 TO number_members-1
print(Members[i])
pb 0
num_runs 0
total_distance 0
120
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
5 A pseudocode solution:
// Program to calculate info from three provided arrays:
// Schools[], MinTemp[] and MaxTemp[]
number_schools 30
121
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
# Initialise, with unreasonable data, the max and minimum tracker variables
highest_temp = -20
lowest_temp = 100
122
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
123
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
Faraday ← 0
Curie ← 0
Counter ← 1
INPUT
Vote
FALSE TRUE
Vote =
Curie ← Curie + 1 Faraday ← Faraday + 1
'Faraday'
Counter ← Counter + 1
FALSE
Counter = 601
TRUE
OUTPUT OUTPUT
STOP
'Curie' + Percent 'Faraday' + Percent
124
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
ELSE
Curie Curie + 1
ENDIF
NEXT
One for each correct identification of error; one for appropriate solution to error.
• Low is declared as 0 / Low will always be lowest value/ Low 0.
• Initialise Low to a value > 200 / Set Low to be the first mark input/ Low 201.
• Comparison for High is incorrect / IF Marks <= High.
• The symbol should be > (accept >=) / IF Marks > High.
• Low is not assigned a value / Marks Low is wrong way round.
• Low must be assigned the value of Marks / Low Marks.
• Average is wrongly calculated / Count ÷ Total is wrong way round.
• Average Total / Count .
125
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b Maximum of two marks – one for each correct validation {cao (correct answer only)}.
c Maximum of three marks from one for each correct data value:
Note:
Missing unitisation zeros – penalise once and then ignore.
Can accept repeated values in a column.
Accept only one output value (reject multiple values even if final value correct).
126
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
START
Counter ← 0
INPUT
Username
FALSE
STOP
Counter ←
Counter + 1
FALSE TRUE
Counter = OUTPUT
599 "No record"
127
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Example pseudocode (this is an example, any working solution will gain marks):
Counter 0
Found FALSE
INPUT Username
128
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Example flowchart:
START
INPUT
product_number
TRUE
LENGTH(product_number)
!=10
FALSE
FALSE TRUE
OUTPUT SUBSTRING(product_number, OUTPUT
"Accepted" 0, 4) !="PROD" "Rejected"
STOP
129
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
Example pseudocode:
INPUT product_number
IF LENGTH (product_number) != 10
THEN
OUTPUT "Rejected"
ELSE
IF SUBSTRING(product_number, 0, 4) != "PROD"
THEN
OUTPUT "Rejected"
ELSE
OUTPUT "Accepted"
ENDIF
ENDIF
CASE OF Score
100: OUTPUT "Excelling"
80: OUTPUT "Good"
60: OUTPUT "Acceptable"
OTHERWISE: OUTPUT "Below expectations"
ENDCASE
Example code:
FUNCTION convert (celsius)
fahrenheit (celsius * 1.8) + 32
RETURN fahrenheit
ENDFUNCTION
130
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b Maximum of six marks from one for each correct data type.
a
START
B
A C
F
E G
I K
STOP
131
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b A age < 10
B, F, J TRUE
D, H, L FALSE
C classification "child"
E age < 18
G classification “junior”
I age < 60
K classification “adult”
M classification “senior”
This would be marked with 1 mark per correct row. Maximum of 8 marks.
However, this is not the only possible solution. If the captions for the options are given as
complete ranges, such as age >9 AND age > 18, there is no necessity for them all to be in order.
StudentName string
StudentID string
ExamMark integer
Percentage real
Comments string
RetestNeeded Boolean
132
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
a newString = UPPER(oldString)
b newString = SUBSTRING(oldString, 8, 1)
c newString = SUBSTRING(oldString, 0, 1)
d newString = SUBSTRING(oldString, 3, 6)
a newString = oldString.upper()
b newString = oldString[8]
c newString = oldString[0]
d newString = oldString[3:9]
Membership
application decision
Receive
Receive details Send decision
supporting Store decision
of applicant to applicant
details
Sorry
Welcome to
application
membership
rejected
133
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
b Maximum of five marks, or maximum of four marks if no example code included in the answer,
from (one mark per line):
17 a Maximum of six marks, from these edits (one mark for each):
• Changed name1 and name2 to something more descriptive.
• Provided a comment for the function.
• Gave the function a more descriptive name.
• Replaced i,j,k,l,m with something a little more related to a set of times.
• Replaced t with an identifier that indicates it is a total in minutes.
• Split RETURN ROUND(t/5) into two lines and used a descriptive identifier.
• Provided a comment to explain what CASE was doing.
• Replaced a,b,c,d,e with identifiers more related to times.
• Replaced ave with average or mean.
• Add a minimum of 3 empty lines to break up the algorithm and make it easier to read.
Example answer:
// A function that takes 5 marathon times in minutes
// as integers and calculates the average
FUNCTION calc_average(t1, t2, t3, t4, t5)
total_minutes t1 + t2 + t3 + t4 + t5
average_minutes ROUND(total_minutes / 5)
134
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
RETURN average_minutes
ENDFUNCTION
INPUT firstname
INPUT lastname
FOR counter 1 TO 5
total_minutes total_minutes + (INPUT marathon_time)
NEXT counter
average_minutes total_minutes / 5
135
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
136
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
print(username, password)
137
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: PROGRAMMING BOOK
c Three marks, one per line; max of two marks if two temporary reads made:
temp_image map[2][2]
map[2][2] map[4][4]
map[4][4] temp_image
Note: temp_image identifier is just an example.
c i One mark:
Name
Omar
Sheila
(order is important)
138