[go: up one dir, main page]

0% found this document useful (0 votes)
23 views11 pages

Solutions

Uploaded by

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

Solutions

Uploaded by

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

Solve the following problems in python:

These exercises will cover all the python syntax we need to know for paper 4 of the syllabus A
level computer science syllabus 9618.

Important notes:
● These exercises only cover the syntax. They do not cover fundamental and abstract
concepts like sorting algorithms, abstract data types etc….
● The checklist on which these exercises are based is complete to the best of my
knowledge, but I cannot guarantee that I have not missed something. Let me know in
the comments if you think I skipped something that could come up on an exam.

The Basics:
Get a number from the user between 10 and 100.
number = input("Enter a number between 10 and 100: ")

Cast the input received from the user to make sure it is an integer.
number = int(input("Enter a number between 10 and 100: "))

Print an error message in case the user did not input a number, and ask the user to try
again
while True:
try:
number = int(input("Enter a number between 10 and 100: "))
except:
print("Sorry, this was not a number, please try again")

Print an error message in case the user input a number outside of the given range (use
if … elif … else …)
while True:
try:
number = int(input("Enter a number between 10 and 100: "))
if (number < 10):
print("Sorry, this was too small. please try again")
elif (number > 100):
print("Sorry, this was too big. please try again")
else:
print("Gotcha")
break
except:
print("Sorry, this was not a number, please try again")

Print an error message in case the user input a number outside of the given range (use
logical operators)
while True:
try:
number = int(input("Enter a number between 10 and 100: "))

1 / 11
if (number < 10 or number > 100):
print("Sorry, this is out of range. please try again")
else:
print("Gotcha")
break
except:
print("Sorry, this was not a number, please try again")

Start with a value of 1 and double it N times, where N is the number given by the user
(use a for-loop). Each iteration print “We have doubled X times resulting in Y”.
value = 1
for i in range(number):
value = value * 2
print("We have doubled " + str(i+1) +
" times, resulting in " + str(value))

Find out how many times you can double the value 1 until it exceeds 1,000,000.
number = 1000000
value = 1
counter = 0
while True:
counter = counter + 1
value = value * 2
print("We have doubled " + str(counter) +
" times, resulting in " + str(value))

if value*2 > number:


break

Get the user’s favourite colour. Using match/case: if the colour is red output ‘You are a
passionate person’, if the colour is blue output ‘You are a reliable person’. In all other
cases output ‘I don’t know that colour’
col = input("What is your favourite colour?")
match col:
case "red":
print("You are very passionate")
case "blue":
print("You are very reliable")
case other:
print("Colour unknown")

2 / 11
Arrays:
Declare an array with the values ‘a’, ‘b’, ‘c’, 1, 2, ‘z’
myArray = ['a', 'b', 'c', 1, 2, 'z']

Loop through the array and print each value.


for i in range(len(myArray)):
print(myArray[i])

Declare a 2D array with the following values:


Name Biology grade English grade

John 9 6

Jane 7 5

Michael 4 7

Mary 8 7
my2DArray = [['Name','Bio grade', 'Eng grade'],
['John',9, 6],
['Jane',7, 5],
['Michael',4, 7],
['Mary',8, 7]]

Use a loop and an if to look up Michael’s English grade.


for i in range(len(my2DArray)):
print(my2DArray[i][0])
if (my2DArray[i][0] == "Michael"):
englishGrade = my2DArray[i][2]

print(englishGrade)

Declare a 2D array with 50 rows and 10 columns. Initialise the array so that each
element has a value of None.
bigArray = [[None for i in range(10)] for i in range(40)]

3 / 11
Functions:
Write a function that asks the user to enter their name and then then print “Hello “ +
name.
def sayHello():
name = input("What is your name? ")
print("Hello " + name)

sayHello()

Write a function that takes 3 string values as parameters, determines the number of
letters in each string, calculates the average of the three lengths, and returns the
resulting value.
def getStrings(string1, string2, string3):
len1 = len(string1)
len2 = len(string2)
len3 = len(string3)

ave = (len1 + len2 + len3)/3


return ave

result = getStrings("abc","defg","hijklmnop")
print(result)

Modify the above function so that it also calculates the sum and returns both the sum
and the average.
def getStrings(string1, string2, string3):
len1 = len(string1)
len2 = len(string2)
len3 = len(string3)

ave = (len1 + len2 + len3)/3


summation = len1 + len2 + len3
return (ave, summation)

(result1, result2) = getStrings("abc","defg","hijklmnop")


print(result1)
print(result2)

The following questions explore the concepts of passing parameters to functions by


value, by reference and by making a variable global.
Declare three variables: a = “pass_by_value”, b = “pass_by_reference”, c =
“global” , d = “not_global” and e = [“mutable1”,”mutable2”]. Print each variable.
Write a function that takes ‘a’ as a parameter passed by value, ‘b’ as a parameter
passed by reference and defines ‘c’ as global.
The function should convert variables ‘a’, ‘b’ and ‘c’ to uppercase. Within the
function print each variable just after they have been converted to uppercase.

4 / 11
After calling the function print each variable. For which variables did the changes
persist?
Modify the function so that the variable ‘d’ is converted to upper case letters. (Do
not pass the variable as a parameter and do not make it global.) Is this possible?
Modify the function so that the first element of variable ‘e’ is also converted to
upper case. (LDo not pass it as a parameter and do not make it global.) Is this
possible? Does the change persist?
a = "pass_by_value"
b = "pass_by_reference"
c = "global"
d = "not_global"
e = ["mutable1","mutable2"]

print("**** before function call ****")


print(a)
print(b)
print(c)
print(d)
print(e)
print("")

def capitalize(a,b):
global c

a = a.upper()
b = b.upper()
c = c.upper()
#d = d.upper()
e[0] = e[0].upper()

print("**** in function call ****")


print(a)
print(b)
print(c)
print(d)
print(e)
print("")

return b

b = capitalize(a, b)

print("**** after function call ****")


print(a)
print(b)
print(c)
print(d)
print(e)

5 / 11
Handling Text files
Open the file ‘student_grades.txt’ for reading.
file = open("student_grades.txt",'r')

Declare an array with length 10 and width 3.


array = [[None for i in range(10)] for i in range(3)]

Read each line of student_grades.txt and populate the first column of the array with the
student’s names, populate the second column with the corresponding Biology grade and
populate the third column with the corresponding English grade. Make sure you read
until the end of the file.
file.readline() #read the first line containing the header
counter = 0
while True:
line = file.readline().strip()
#check for eof
if (line == ""):
break

n = line.find(',')
name = line[0:n]
line = line[n+1:len(line)]
n = line.find(',')
bio = line[0:n]
eng = line[n+1:len(line)]

array[0][counter] = name
array[1][counter] = bio
array[2][counter] = eng

counter += 1

Close the file.


file.close()

Create a new file: ‘whole_class_summary.txt’ and write the following line to the file. Then
close the file again.
Summary for class 6A
file = open("whole_class_summary.txt",'w')
file.write("Summary for class 6A\n")
file.close()

Open the file for append and, line-by-line, add each student’s name followed by their
average grade. Then close the file again.
file = open("whole_class_summary.txt",'a')
counter = 0
while True:

6 / 11
name = array[0][counter]
if name == None:
break
average = (int(array[1][counter]) + int(array[2][counter]))/2

file.write(name + "," + str(average) +"\n")


counter += 1
file.close()

7 / 11
Classes
Create a class ‘Caveman’. The class has the following private properties:
○ hungry (boolean)
○ name (string)
The constructor takes a string as a parameter which sets the name of the Caveman. The
property hungry is set to True by default when a new instance of ‘Caveman’ is created.
We also output a message “[name] was born”.
The class has one public method named ‘eat’. In this method we set the value of hungry
to False and we output “Gobble gobble gobble”.
The class has two getters:
○ isHungry() returns the value of __hungry
○ getName() returns the name of the caveman
The class also has a destructor. In the destructor we output “Oh no! A sabre tooth tiger
ate [name]!”.
class Caveman:
def __init__(self,name):
self.__name = name
self.__hungry = True
print(name + " was born.")

def eat(self):
self.__hungry = False
print("Gobble gobble gobble")

def isHungry(self):
return self.__hungry

def getName(self):
return(self.__name)

def __del__(self):
print("Oh no! A sabre tooth tiger ate " + self.__name)

glug = Caveman("Glug")
glug.eat()

Create a new instance of Caveman, a caveman named ‘Glug’.


Sadly ‘Glug’ one day met his demise. Delete the instance of ‘Glug’
glug = Caveman("Glug")
del glug

Create a new class named ‘ModernMan’. The class inherits all the properties and
methods of ‘Caveman’
But he gets an additional private property and an additional method:
○ bankBalance (integer) which has an initial value of 0
○ showBalance() which prints out the current balance.

8 / 11
ModernMan also eats in a much more polite way, unless he is hungry. Override the eat
method so then he outputs “chew chew” in case he is not hungry. But if he is hungry then
run the original method from the super class.
Before ModernMan dies he’s not so worried about sabre tooth tigers but is more
concerned with updating his last will and testament. Override the destructor so that he
outputs “[name] updates his/her last will and testament” instead.
Add a method named ‘earnMoney’. The method can be called with no parameters in
which case 10 is added to the bank balance. Optionally, we can specify the amount we
want to add to the balance as one of the parameters. Implement this using overriding.
class ModernMan(Caveman):
def __init__(self,name):
super().__init__(name)
self.__bankBalance = 0

def showBalance(self):
print(self.__bankBalance)

def eat(self):
if super().isHungry():
super().eat()
else:
print("Chew chew chew")

def earnMoney(self, amount = None):


if amount == None:
self.__bankBalance += 10
else:
self.__bankBalance += amount

def __del__(self):
print(self.getName() +
" is updating his last will and testament.")

greg = ModernMan("Gregory")
print(greg.isHungry())
greg.eat()
greg.eat()
greg.earnMoney()
greg.earnMoney(12)
greg.showBalance()
del greg

9 / 11
Handling Binary Files
Create a class named Student with the following properties:
○ Name (string)
○ StudentID (int)
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id

Create an array of 5 students with the following values:


○ Mark, 1
○ George, 3
○ Amy, 4
○ Clara, 9
○ Anne, 2
ListOfStudents = [Student("None",0) for i in range(5)]
ListOfStudents[0].name = "Mark"
ListOfStudents[1].name = "George"
ListOfStudents[2].name = "Amy"
ListOfStudents[3].name = "Clara"
ListOfStudents[4].name = "Anne"
ListOfStudents[0].student_id = 1
ListOfStudents[1].student_id = 3
ListOfStudents[2].student_id = 4
ListOfStudents[3].student_id = 9
ListOfStudents[4].student_id = 2

Create a new file and add Mark to it. Then close the file.
import pickle
file = open('student_records.dat','wb')
pickle.dump(ListOfStudents[0],file)
file.close()

Append the file with George, Amy and Clara. Then close the file.
file = open('student_records.dat','ab')
pickle.dump(ListOfStudents[1],file)
pickle.dump(ListOfStudents[2],file)
pickle.dump(ListOfStudents[3],file)
file.close()

Read the third record from the file and print the id. Then close the file.
file = open('student_records.dat','rb')
studentRecord = pickle.load(file)
studentRecord = pickle.load(file)
studentRecord = pickle.load(file)
print(studentRecord.student_id)
file.close()

10 / 11
Have the user input a student name. Read the file and search for a student with the
name. Output the student_id of the student or "not found"
name = input("please enter a name: ")
file = open('student_records.dat','rb')
while True:
try:
studentRecord = pickle.load(file)
except EOFError:
print ("could not find the record")
break
if studentRecord.name == name:
print (studentRecord.student_id)
break

Insert the student Anne into the file so that the students are arranged in order of student
id.
file = open('student_records.dat','rb')
file2 = open('temp.dat','wb')
dumped = False
while True:
try:
studentRecord = pickle.load(file)
except EOFError:
if dumped == False:
pickle.dump(ListOfStudents[4],file2)
dumped = True
break

if studentRecord.student_id >
ListOfStudents[4].student_id and not dumped:
pickle.dump(ListOfStudents[4],file2)
dumped = True

pickle.dump(studentRecord,file2)

file.close()
file2.close()

import os
os.remove('student_records.dat')
os.rename('temp.dat','student_records.dat')

11 / 11

You might also like