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

Python Exercises for A-Level 9618 Syntax

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)
15 views11 pages

Python Exercises for A-Level 9618 Syntax

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

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 = [Link]()
b = [Link]()
c = [Link]()
#d = [Link]()
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.
[Link]() #read the first line containing the header
counter = 0
while True:
line = [Link]().strip()
#check for eof
if (line == ""):
break

n = [Link](',')
name = line[0:n]
line = line[n+1:len(line)]
n = [Link](',')
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.


[Link]()

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')
[Link]("Summary for class 6A\n")
[Link]()

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

[Link](name + "," + str(average) +"\n")


counter += 1
[Link]()

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")
[Link]()

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([Link]() +
" is updating his last will and testament.")

greg = ModernMan("Gregory")
print([Link]())
[Link]()
[Link]()
[Link]()
[Link](12)
[Link]()
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):
[Link] = 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')
[Link](ListOfStudents[0],file)
[Link]()

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

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

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 = [Link](file)
except EOFError:
print ("could not find the record")
break
if [Link] == 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('[Link]','wb')
dumped = False
while True:
try:
studentRecord = [Link](file)
except EOFError:
if dumped == False:
[Link](ListOfStudents[4],file2)
dumped = True
break

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

[Link](studentRecord,file2)

[Link]()
[Link]()

import os
[Link]('student_records.dat')
[Link]('[Link]','student_records.dat')

11 / 11

Common questions

Powered by AI

Overriding methods in subclasses allows for extending or altering the functionality of base class methods, providing more specialized behavior in derived classes. In Python, this is achieved by defining a method in the subclass with the same signature as the one in the base class. For example, the 'ModernMan' class overrides the `eat` method of the 'Caveman' class. While the base method outputs 'Gobble gobble gobble', the overridden method outputs 'chew chew' if the 'ModernMan' is not hungry, otherwise it reverts to the base class's method if he is hungry. This demonstrates tailored functionality while maintaining a connection to the original behavior .

Class destructors in object-oriented programming are special methods called when an object is about to be destroyed, allowing for resource management and clean-up tasks. Implemented in Python using the `__del__` method, destructors can be used to close files, release memory, or output specific messages when an object is no longer needed. In the 'Caveman' class example, the destructor outputs a message indicating the demise of the caveman. This highlights its utility in cases where the object's end-of-life must be explicitly managed or logged .

In Python, parameter passing can be understood through the concepts of 'pass-by-value' and 'pass-by-reference'. In the case of immutable objects like integers and strings, passing them to functions behaves like pass-by-value, meaning the original object is not altered outside the function. For mutable objects like lists, it behaves like pass-by-reference, where changes within the function reflect on the original object. For example, modifying a list within a function changes it globally, while modifying a string or integer does not. This distinction is shown in modifying variables within functions, where a string passed to a function remains unchanged unless explicitly returned, while list modifications persist .

A common method to store data such as grades using a 2D array involves defining a two-dimensional list where each sub-list represents a student and their respective grades. Retrieval is straightforward by iterating through the array rows and checking specific conditions. For example, to find a specific student's English grade, loop through each student, check the name column, and if it matches 'Michael', access the relevant grade column. This method facilitates organized data storage and efficient data retrieval by leveraging structured indexing .

Handling arrays of objects involves more complexity than primitive data types due to the need for managing object properties and behaviors. In Python, arrays of objects, such as lists of instances of a custom class, require iteration over object attributes for manipulation. For example, manipulating a list of 'Student' instances involves accessing and modifying properties through methods defined in the class, rather than simple operations available for primitive types. This process includes creating constructors for initialization, defining methods for manipulation, and employing iterations to traverse and process each object, thus requiring a sound understanding of both object-oriented programming and data structures .

File operations in Python, such as open, read, write, and append, are essential for managing and persisting data like student records. This approach enables efficient data storage and retrieval, offering persistence across program executions. For instance, records can be serialized using the `pickle` module, allowing complex data structures to be written to files and retrieved later. Such operations are advantageous for large datasets where in-memory operations would be inefficient. Managing files includes opening for specific modes (reading, writing, appending), processing data line-by-line, and ensuring proper closure of files to release system resources .

Challenges in managing variable scope arise when trying to modify variable values (like 'd') within functions without passing them as parameters or making them global. In Python, such changes typically require accessing the variable through its enclosing namespace, as direct modification is restricted to prevent side effects. Attempting to convert 'd' to uppercase without making it global or passing as a parameter isn’t feasible directly, as local method scope isolates the variable 'd' from external modifications, a principle aimed at preserving data integrity and avoiding unintended modifications across scopes .

To repeatedly prompt the user for a valid integer within a range, use a while loop with a try-except block. First, attempt to cast the input to an integer using int(input(...)). Then, check if the integer is within the desired range with conditional statements (if...elif...else). If the input is not a valid integer, catch the exception using 'except' and prompt the user to try again. In this way, the loop continues until a valid number is input, handling both invalid numbers and inputs outside the range effectively .

The `match/case` syntax provides a clear and efficient way to handle multiple conditional cases by matching the value of a variable against different patterns. In the context of determining a user's favorite color, it allows for concise and organized code where each case directly corresponds to a potential input. This reduces the need for multiple if-elif statements, making the code more readable. For example, by using `case 'red':` or `case 'blue':`, distinct outputs can be provided depending on the color input, improving code elegance .

Using exception handling is crucial in Python for managing errors that arise during input operations. It allows the program to continue running and prompt the user again, preventing crashes from invalid inputs. For instance, when prompting a user to input a number, enclosing the conversion attempt in a try block and catching errors with an except block ensures that non-numeric inputs do not cause the program to fail. Instead, users receive a message indicating the error and are asked to try again, promoting robustness in user interaction .

You might also like