IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Worksheet 1 | Lesson 1 | B2.3.4
Functions: Reusable Code
Name: ________________________________ Date: ________________
Part A: Understanding
Q1. [2 marks]
Define the term function in the context of programming. Your definition must include the words
parameter and reusable.
Q2. Complete the Code [4 marks]
Fill in the four blanks to make the calculate_area function work correctly.
def calculate_area( __________ , __________ ):
"""Return the area of a rectangle."""
return __________ * __________
area = calculate_area(5, 3) # area should equal ____
print(area)
Q3. Code Tracing [4 marks]
Without running the code, fill in the trace table showing the value of each variable at each step.
def triple(n):
result = n * 3
return result
x = triple(4)
y = triple(x)
print(y)
Step n result x y Output
triple(4)
x = result
triple(x)
print(y)
Part B: Apply
Q4. Write and Test Functions [6 marks]
Write all three functions in VS Code, then test each with at least 3 different inputs. Paste or describe
your tests below.
• celsius_to_fahrenheit(celsius) → returns (celsius × 9/5) + 32
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
• is_passing(score, pass_mark=60) → returns True if score is at or above pass_mark
• bmi(weight_kg, height_m) → returns weight_kg / height_m squared
Write your three function definitions here (or describe them if you coded in VS Code):
What inputs did you use for each test? What did you learn from testing?
Going Further
• Write a fourth function describe_bmi(bmi_value) that returns a category string: Underweight,
Normal, Overweight, or Obese
• Then write a fifth function full_report(weight_kg, height_m) that calls both bmi() and
describe_bmi() and returns a formatted single string
• What happens if height_m is 0? Add a check for this edge case
Part C: IB-Style
Explain two benefits of using functions when writing a large program. Use a specific example to support
each benefit. [4 marks]
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Checklist
[] I can write a function with parameters and a return value
[] I can explain the difference between a parameter and an argument
[] I can trace code that calls functions and predict the output
[] I can explain at least two benefits of using functions
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Worksheet 2 | Lesson 2 | B2.3.4
Scope: Local vs Global Variables
Name: ________________________________ Date: ________________
Part A: Understanding
Q1. Classify Variables [4 marks]
Write L (local) or G (global) next to each comment. Then write one sentence justifying each decision.
school = 'IB Academy' # ___
total_students = 120 # ___
def enrol(name, age):
message = f'{name} enrolled' # ___
year_group = age - 5 # ___
print(f'{message} at {school}')
Justifications:
Q2. Predict Output or Error [4 marks]
For each snippet, write the exact output OR write 'NameError' or 'UnboundLocalError'. Then explain
WHY in one sentence.
x = 5 total = 0
def f(): def add(n):
x = 10 total += n
print(x) add(5)
f() print(total)
print(x)
Output or Error:
Output:
Why?
Why?
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Part B: Apply
Q3. Fix the Scope Bugs [6 marks]
Each program below has a scope error. Identify the error, explain it, and write the corrected version.
Bug 1:
def set_username(name):
username = name
set_username('Alice')
print(username) # what is wrong?
Error:
Corrected code:
Bug 2:
count = 0
def increment():
count += 1 # what is wrong?
increment()
print(count)
Error:
Corrected code:
Q4. Design Task [4 marks]
Write a program for a simple login system. Use a global variable login_attempts that starts at 0. Write a
function attempt_login(password) that increments the counter and prints a message. Use the global
keyword correctly. Block access after 3 failed attempts.
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Going Further
• Research Python closures: write a function make_counter() that returns another function
• The returned function should increment and return a count value each time it is called
• Explain in 3 sentences how a closure differs from using the global keyword
Part C: IB-Style
Distinguish between a local variable and a global variable in Python. [2] Give one example of a situation
where a global variable is the appropriate design choice, and explain why. [2]
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Worksheet 3 | Lesson 5-6 | B3.1.4
Classes and Objects
Name: ________________________________ Date: ________________
Part A: Understanding
Q1. Matching [4 marks]
Match each term to its description.
Term Description
1. Class _____ A. A specific instance created from the blueprint
B. A variable that stores data belonging to an
2. Object _____
object
3. Attribute _____ C. A function defined inside a class
D. A blueprint or template defining structure and
4. Method _____
behaviour
Q2. Code Tracing [6 marks]
Trace the code below and fill in the table. Then answer the follow-up question.
class Book:
def __init__(self, title, pages):
[Link] = title
[Link] = pages
self.is_borrowed = False
def borrow(self):
self.is_borrowed = True
print(f"'{[Link]}' borrowed")
b1 = Book('Dune', 412)
b2 = Book('1984', 328)
[Link]()
print(b1.is_borrowed)
print(b2.is_borrowed)
Object .title .pages .is_borrowed
b1 (after creation)
b2 (after creation)
b1 (after borrow())
b2 (unchanged)
Why does b2.is_borrowed still print False after [Link]() was called?
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Part B: Apply
Q3. Design and Write a Class [8 marks]
Design and implement a Smartphone class from scratch.
The class must have:
• Attributes set in __init__: brand, model, storage_gb, battery_level (starts at 100), installed_apps
(starts as empty list)
• charge(amount): increases battery_level but never above 100
• install_app(name, size_gb): adds name to installed_apps, reduces storage_gb
• use_app(name): drains 5% battery if app is installed; prints an error if not installed
• get_status(): returns a formatted summary of all attributes
Plan your design first (attribute types, what each method returns or changes):
Write your class in VS Code. Summarise the key methods below:
Create 2 Smartphone objects. List the calls you made and what each returned or printed:
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Going Further
• Add an uninstall_app(name) method that restores the storage if the app is found
• Add a factory class method from_dict(cls, data) that creates a Smartphone from a dictionary
• What edge cases did you find? How did you handle them?
Part C: IB-Style
Construct a Python class called Product with attributes name, price, and stock_count. Include a method
sell(quantity) that reduces stock by quantity and returns the total cost. The method should handle the
case where stock is insufficient. [4 marks]
Checklist
[ ] I can explain the difference between a class and an object
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
[ ] I can write a class with __init__, attributes, and methods
[ ] I can create multiple instances from one class with different data
[ ] I understand why changing one object does not affect other objects
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Worksheet 4 | Lesson 8-9 | B3.1.2
UML Class Diagrams
Name: ________________________________ Date: ________________
Part A: Reading UML
Q1. Interpret the Diagram [5 marks]
Study the UML diagram below, then answer the questions.
Student
- __student_id : str
- __name : str
+ grade_level : int
- __gpa : float
+ __init__(id: str, name: str, level: int) :
None
+ add_grade(subject: str, score: float) : None
+ get_gpa() : float
- __calculate_avg() : float
a) How many private attributes does this class have? _____
b) What does the - symbol before an attribute name indicate?
c) What does the + symbol indicate?
d) Which method should only be called from inside the class? Why?
Q2. UML to Python [6 marks]
Write the Python class for the Student UML above. Implement __init__ and get_gpa() fully. Use correct
private/public naming.
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Part B: Drawing UML
Q3. Python to UML [4 marks]
Draw the UML diagram for the Python class below in the empty template on the right. Include access
modifiers and data types.
class Rectangle: Draw UML here:
def __init__(self, w: float, h:
float):
self.__width = w
self.__height = h
def get_area(self) -> float:
return self.__width *
self.__height
def get_perimeter(self) -> float:
return 2 * (self.__width +
self.__height)
def is_square(self) -> bool:
return self.__width ==
self.__height
Part C: Design Task
Q4. Design and Implement [8 marks]
Design the UML for a Library system BEFORE writing any code. The Library manages Books. A Book
has isbn, title, author, and can be borrowed and returned.
Step 1 — Draw the UML for both classes on paper or [Link]. Show the relationship between Library
and Book.
Step 2 — Implement both classes in Python. Test that a Book can be borrowed and returned through
the Library interface.
Step 3 — Answer this design question: why does borrow() belong in Book rather than in Library?
Going Further
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
• Add a third class Member with member_id, name, and borrowed_books list
• Show in your UML how Member relates to both Book and Library
• Implement Member.borrow_book(book) and demonstrate a full borrow-and-return cycle
Part D: IB-Style
Distinguish between a class attribute and an instance attribute in Python. [2] Give one example of each
in the context of a student management system. [2]
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Worksheet 5 | Lesson 12-13 | B3.1.5
Encapsulation and Information Hiding
Name: ________________________________ Date: ________________
Part A: Understanding
Q1. Access Modifiers [3 marks]
For each scenario, write the correct Python naming convention: self.x (public), self._x (protected), or
self.__x (private).
Scenario Convention
An attribute freely readable and writable by any
code
An attribute intended only for this class and its
subclasses
An attribute strongly restricted to inside this class
only
Q2. Spot the Problem [3 marks]
This code has a serious design problem. Identify it, explain the security risk, and describe how to fix it
without showing the code (yet).
class PatientRecord:
def __init__(self, patient_id, diagnosis):
self.patient_id = patient_id
[Link] = diagnosis
record = PatientRecord('P001', 'Hypertension')
[Link] = 'Healthy' # is this a problem?
The problem:
The security risk this creates:
Part B: Apply
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Q3. Rebuild with Encapsulation [8 marks]
Rewrite the PatientRecord class below with proper encapsulation.
Requirements:
• diagnosis and patient_id must be private
• Add a get_diagnosis(authorised=False) getter that only returns the diagnosis if authorised is
True
• Add a get_patient_id() getter
• Add a set_diagnosis(new_diagnosis) setter that validates the new value is a non-empty string
• Use @property and @[Link] for diagnosis
Write your implementation in VS Code. Summarise the key design decisions here:
Test your code by trying to set an invalid diagnosis and show what happens:
Q4. @property Practice [4 marks]
Complete the class below by filling in every blank. The age property must reject values outside 0-150.
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
______________ # decorator
def name(self):
______________ # return the name
______________ # decorator
def age(self):
______________ # return the age
@[Link]
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
def age(self, value):
if ______________: # check valid range
raise ValueError(f'Invalid age: {value}')
self._age = ______________
Going Further
• Add a read-only @property called initials that returns the first letter of each word in the name
• Add @property display_name that returns the name in UPPER CASE without changing the
stored value
• Design a MedicalRecord class where doctor-only and patient-only data have different access
methods
Part C: IB-Style
Explain the importance of limiting access to class members to maintain the integrity and security of an
object's state. Use a specific example from a banking or medical system. [4 marks]
Checklist
[] I can explain encapsulation in my own words with a real example
[] I can use __ to make attributes private and know what name mangling does
[] I can write @property getters and setters with validation
[] I can justify why private attributes improve security and data integrity
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Worksheet 6 | Lesson 14-16 | B3.1.1
Inheritance, Overriding, and Polymorphism
Name: ________________________________ Date: ________________
Part A: Understanding
Q1. Trace the Output [6 marks]
Trace this code and fill in the table. Predict the output of each print() statement.
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
return f'{[Link]} makes a sound'
def breathe(self):
return f'{[Link]} breathes'
class Dog(Animal):
def speak(self): # override
return f'{[Link]} barks: Woof!'
def fetch(self):
return f'{[Link]} fetches!'
class GuideDog(Dog):
def __init__(self, name, owner):
super().__init__(name)
[Link] = owner
def guide(self):
return f'{[Link]} guides {[Link]}'
d = Dog('Rex')
g = GuideDog('Buddy', 'Alice')
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print(isinstance(g, Animal))
Which class provides this
Statement Output
method?
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print(isinstance(g, Animal)) Built-in
Q2. Polymorphism Analysis [4 marks]
Read this code and answer the questions.
shapes = [Circle(5), Rectangle(4, 6), Triangle(3, 8)]
for shape in shapes:
print([Link]())
1. What is polymorphism? Define it in one sentence.
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
2. How does the for loop above demonstrate polymorphism?
3. If you added a Pentagon class with a describe() method, would the loop code need to change?
Explain.
4. What design advantage does this demonstrate?
Part B: Apply
Q3. Build a Class Hierarchy [8 marks]
Build a Vehicle class hierarchy.
Vehicle (parent):
• __init__(make, model): sets make, model, speed = 0
• accelerate(amount): increases speed, returns a formatted string
• describe(): returns make + model
ElectricVehicle(Vehicle):
• __init__(make, model, battery_range): calls super().__init__, adds battery_range
• start(): completely OVERRIDE [Link]() to return a silent-start message
• describe(): EXTEND [Link]() using super() to append '| Electric'
HybridVehicle(Vehicle):
• start(): EXTEND [Link]() using super() to append 'then switches to electric'
Create one of each. Call start() on all three and show the different outputs.
Then print ElectricVehicle.__mro__ and explain what it shows.
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
When did you use override (replace)? When did you use super() to extend? Explain your decisions.
Going Further
• Add isinstance() checks to confirm that an ElectricVehicle IS-A Vehicle and IS-A
ElectricVehicle
• Design a polymorphic function describe_fleet(vehicles) that works with any list of Vehicle
objects
• Research diamond inheritance: what happens when class D inherits from both B and C, which
both inherit from A? Run D.__mro__ and explain the result
Part C: IB-Style
Evaluate the use of inheritance and polymorphism when designing a large software system such as a
hospital management platform. Include at least two advantages and one disadvantage. [6 marks]
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Checklist
[] I can write a child class that inherits from a parent using class Child(Parent)
[] I can use super().__init__() to call the parent constructor
[] I can distinguish between overriding (replace) and extending (super() + add)
[] I can explain polymorphism using a real-world analogy and a code example
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Worksheet 7 | Lesson 18 | All Outcomes B2.3.4 and B3.1.1-B3.1.5
Unit Review Assessment
Name: ________________________________ Date: ________________
Part A: Short Answer [10 marks]
A1. [2]
Define encapsulation.
A2. [2]
Distinguish between a class variable and an instance variable.
A3. [2]
State TWO advantages of using OOP in a large software project.
A4. [2]
Explain the role of __init__ and what self refers to inside it.
A5. [2]
What does @staticmethod indicate? Give one appropriate use case.
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Part B: Code Reading [8 marks]
B1-B4. Study the code then answer all four questions.
class Vehicle:
total = 0
def __init__(self, make, speed):
[Link] = make
self.__speed = speed
[Link] += 1
def get_speed(self): return self.__speed
def describe(self): return f'{[Link]}: {self.__speed} km/h'
class Car(Vehicle):
def __init__(self, make, speed, doors):
super().__init__(make, speed)
[Link] = doors
def describe(self): # override
return super().describe() + f' ({[Link]} doors)'
v = Vehicle('Truck', 90)
c = Car('BMW', 180, 4)
for x in [v, c]:
print([Link]())
B1. [2]
Identify which attribute uses encapsulation. Explain why it was made private.
B2. [2]
Trace the output of the for loop.
B3. [2]
What OOP concept does the for loop demonstrate? Explain in 2 sentences.
B4. [2]
What is the value of [Link] after both objects are created? _____ Is this a class or instance
variable? _____ Explain.
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
Part C: Construct Code [12 marks]
C1. Build from UML [6 marks]
Write a Python class for this UML. Then add an ElectricCar child class that overrides describe() to
include battery information.
Car
- __make : str
- __model : str
- __year : int
- __mileage : float
+ __init__(make, model, year) : None
+ drive(km: float) : None
+ describe() : str
+ get_mileage() : float
C2. Write a static method [2 marks]
Add a @staticmethod called validate_year(year) to the Car class above that returns True if the year is
between 1886 (first car) and the current year.
Page
IB DP Computer Science SL | OOP Student Worksheets | Python 3, VS Code
C3. Extend the hierarchy [4 marks]
Write an ElectricCar(Car) class that overrides describe() to include the battery_range_km attribute. Use
super() to get the base description first.
Part D: Evaluate [6 marks]
Evaluate the use of OOP for designing a hospital patient management system. Include two advantages
relevant to this context, one disadvantage, and a justified conclusion. [6 marks]
Unit Checklist: Tick Every Concept You Can Explain
[] Functions, parameters, return values [ ] @staticmethod and @classmethod
[] Local vs global scope, LEGB rule [ ] Encapsulation and private attributes
[] Modularization and imports [ ] @property getter and setter
[] Class vs object [ ] Inheritance and super()
[] __init__ and self [ ] Method overriding vs extension
[] Instance methods [ ] Polymorphism
[] UML class diagrams [ ] OOP advantages and disadvantages
[] Class vs instance variables [ ] IB command terms: evaluate, distinguish,
construct
Page