Object-Oriented Programming (OOP)
Multiple Choice
True or False: A class definition provides a pattern for creating objects, but doesn’t make any objects itself.
True
False
True or False: All instances of a class have the same attribute values.
True
False
True or False: An object’s attribute values cannot be accessed from outside the class.
True
False
What is the difference between a class and an object?
A class is a collection of objects
A class is a blueprint; an object is a specific instance of that blueprint
They are the same in Python
An object can contain classes, but not the other way around
True or False: Because class definitions have attributes, local variables are not allowed inside method definitions.
True
False
What does it mean to “instantiate” a class?
Define the class
Import a module
Create an object from a class
Define attributes
True or False: The constructor of a class is only called once in a program, no matter how many objects of that class are constructed.
True
False
The first parameter of any method is _____ and it is given a reference to the object the method was called on.
me
self
init
this
current
An instance of a class is stored in the:
stack
heap
output
True or False: Once attributes are initialized in the initializer/constructor, the values cannot be changed.
True
False
True or False: A class definition introduces a new data type, or type of object, in your program.
True
False
SOLUTIONS
True
False
False
A class is a blueprint; an object is a specific instance of that blueprint
False
Create an object from a class
False
self
heap
False
True
Select All That Apply
Consider the following code listing. Select all lines on which any of the concepts below are found. Select if the concept is not in the code listing.
class Point:
x: float
y: float
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def flip(self) -> None:
temp: float = self.x
self.x = self.y
self.y = temp
def shift_y(self, dy: float) -> None:
self.y += dy
def diff(self) -> float:
return self.x - self.yConstructor Declaration
1
2
5
9
11
Attribute Declaration
2
3
6
7
10
Attribute Initialization
2
3
6
7
10
Method Declaration
1
9
10
14
17
Local Variable Declaration
2
3
6
7
10
Instantiation
1
5
9
10
N/A
SOLUTIONS
Line 5 only
Lines 2 and 3
Lines 6 and 7
Lines 9, 14, and 17
Line 10
N/A
Short Answer
What does
selfrefer to in Python classes?Similar to how a function is first defined then called, a class is first defined then ____.
When a method is called, do you have to pass an argument to the
selfparameter?When is
selfused outside of a class definition?Use the following point class to answer the questions.
class Point: x: float y: float def __init__(self, x: float, y: float): self.x = x self.y = y def flip(self) -> None: temp: float = self.x self.x = self.y self.y = temp def shift_y(self, dy: float) -> None: self.y += dy def diff(self) -> float: return self.x - self.y5.1. Write a line of code to create an explicitly typed instance of the Point class called my_point with an x of 3.7 and y of 2.3.
5.2. Write a line of code to change the value of the my_point variable’s x attribute to 2.0.
5.3. Write a line of code to cause the my_point variable’s y attribute to increase by 1.0 using a method call.
5.4. Write a line of code to declare an explicitly typed variable named x. Initialize x to the result of calling the diff method on my_point.
SOLUTIONS
selfrefers to the current instance of the class that the methods will operate on if those methods are called in the future on an instance of that class.Instantiated
No! When you call the constructor for a class,
selfis automatically made by python in order for the rest of the constructor to finish making the object. In the case of other methods, python knows thatselfis the object that you called the method on, often the variable name that comes before the method call (e.g. formy_point.shift_y(1.0),selfismy_point).selfis not used outside of a class definition. Outside of a class definition you use the name of the variable storing an object to refer to it.
5.1. my_point: Point = Point(x=3.7, y=2.3)
5.2. my_point.x = 2.0
5.3. my_point.shift_y(1.0)
5.4. x: float = my_point.diff()
Function + Method-Writing With Instances of a Class
Course
- Write a function (NOT A METHOD) called
find_courses. Given the followingCourseclass definition,find_coursesshould take in alist[Course]and astrprerequisite to search for. The function should return a list of thenamesof each Course whoselevelis 400+ and whoseprerequisiteslist contains the given string.
class Course:
"""Models the idea of a UNC course."""
name: str
level: int
prerequisites: list[str]
- Write a method called
is_valid_coursefor theCourseclass. The method should take in astrprerequisite and return aboolthat represents whether the course’slevelis 400+ and if itsprerequisiteslist contains the given string.
Class-Writing
Car
Write a Python class called Car that represents a basic model of a car with the following specifications:
- Include attributes
make: str,model: str,year: int,color: str, andmileage: float.
- Write a constructor to initialize all attributes.
- Implement a method for updating the mileage of the car,
update_mileage, that takes an amount ofmiles: floatas input and updated the mileage attribute. - Implement a method displaying the car’s attribute information as a string called
display_info. It should just print the information and not return anything. (You can take creative liberty, as long as it prints out all attributes!) - Implement a function (NOT a method) called
calculate_depreciationthat calculates the depreciation of the car by taking aCarobject as input anddepreciation_rate: floatand returns the mileage multiplied by the depreciation rate.
Practice calling these methods by instantiating a new car object and calling them!
Class Writing + Magic Methods
HotCocoa
Create a class called HotCocoa with the following specifications:
Each
HotCocoaobject has aboolattribute calledhas_whip, astrattribute calledflavor, and twointattributes calledmarshmallow_countandsweetness.The class should have a constructor that takes in and sets up each of its attribute’s values.
Write a method called
mallow_adderthat takes in anintcalledmallows, increases themarshmallow_countby that amount, and increases thesweetnessby that amount times 2.Write a
__str__magic method that displays (aka returns a string with) the details of the hot cocoa order mimicing the following:- If it has whipped cream:
"A <flavor> cocoa with whip, <marshmallow_count> marshmallows, and level <sweetness> sweetness. - If it doesn’t have whipped cream:
"A <flavor> cocoa without whip, <marshmallow_count> marshmallows, and level <sweetness> sweetness.
- If it has whipped cream:
Write an
order_costfunction that takes as input alistofHotCocoaobjects to represent an order and returns the total cost of the order. AHotCocoawith whip is $2.50 and without whip is $2.00.
Instantiation Practice
Create an instance of
HotCocoacalledmy_orderwith no whip,"vanilla"flavor, 5 marshmallows, and sweetness level 2.Add whipped cream. (Change
has_whiptoTrue.)Add 2 marshmallows using
mallow_adder.Create another
HotCocoainstance calledviktoryas_orderwith whip,"peppermint"flavor, 10 marshmallows, and sweetness level 2.Calculate the cost of
[my_order, viktoryas_order]by callingorder_cost.Print out the details of the
HotCocoainstancemy_order.
TimeSpent
Create a class called TimeSpent with the following specifications:
Each
TimeSpentobject has astrattribute calledname, astrattribute calledpurpose, and anintattribute calledminutes.The class should have a constructor that takes in and sets up each of its attribute’s values.
Write a method called
add_timethat takes in anintand increases theminutesattribute by this amount. The method should returnNone.Write an
__add__magic method that takes in anintcalledadded_minutesand returns a newTimeSpentobject with the same attribute values except thatminutesis increased byadded_minutes.Write a method called
resetthat resets the amount of time that is stored in theminutesattribute. The method should also return the amount that was stored inminutes.Write a
__str__magic method returns a line reporting information about the currentTimeSpentobject. Suppose aTimeSpentobject hasname=“Ariana”,purpose=“screen time”, andminutes=130. The method should return:“Ariana has spent 2 hours and 10 minutes on screen time.”Write a function called
most_by_purposethat takes as input alistofTimeSpentobjects and astrto represent a purpose, and returns the name of the person who spent the most time doing that specific activity.- Example usage:
>>> a: TimeSpent = TimeSpent("Alyssa", "studying", 5) >>> b: TimeSpent = TimeSpent("Alyssa", "doom scrolling", 100) >>> c: TimeSpent = TimeSpent("Vrinda", "studying", 200) >>> most_by_purpose([a, b, c], "studying") 'Vrinda'
- Example usage:
Solutions
SOLUTIONS
Function + Method Writing With Class Objects
Course Solution
def find_courses(courses: list[Course], prereq: str) -> list[str]:
"""Finds 400+ level courses with the given prereq."""
results: list[str] = []
for c in courses:
if c.level >= 400:
for p in c.prerequisites:
if p == prereq:
results.append(c.name)
return results
def is_valid_course(self, prereq: str) -> bool:
"""Checks if this course is 400+ level and has the given prereq."""
if self.level < 400:
return False
else:
for p in self.prerequisites:
if p == prereq:
return True
return False
Class-Writing
Car solution
class Car:
make: str
model: str
year: int
color: str
mileage: float
def __init__(self, make: str, model: str, year: int, color: str, mileage: float):
self.make = make
self.model = model
self.year = year
self.color = color
self.mileage = mileage
def update_mileage(self, miles: float) -> None:
self.mileage += miles
def display_info(self) -> None:
info: str = f"This car is a {self.color}, {self. year} {self.make} {self.model} with {self.mileage} miles."
print(info)
def calculate_depreciation(vehicle: Car, depreciation_rate: float) -> float:
return vehicle.mileage * depreciation_rate
to practice instantiating:
my_ride: Car = Car("Honda", "CRV", "2015", "blue", 75000.00)
my_ride.update_mileage(5000.25)
my_ride.display_info()
calculate_depreciation(my_ride, .01)
HotCocoa solution
class HotCocoa:
has_whip: bool
flavor: str
marshmallow_count: int
sweetness: int
def __init__(self, whip: bool, flavor: str, marshmallows: int, sweetness: int):
self.has_whip = whip
self.flavor = flavor
self.marshmallow_count = marshmallows
self.sweetness = sweetness
def mallow_adder(self, mallows: int) -> None:
self.marshmallow_count += mallows
self.sweetness += (mallows * 2)
def __str__(self) -> str:
if self.has_whip:
return f"A {self.flavor} cocoa with whip, {self.marshmallow_count} marshmallows, and level {self.sweetness} sweetness."
else:
return f"A {self.flavor} cocoa without whip, {self.marshmallow_count} marshmallows, and level {self.sweetness} sweetness."
def order_cost(order: list[HotCocoa]) -> float:
cost: float = 0.0
for cocoa in order:
if cocoa.has_whip:
cost += 2.50
else:
cost += 2.00
return cost
Instantiation
my_order: HotCocoa = HotCocoa(False, "vanilla", 5, 2)
# Add whipped cream. (Change has_whip to True.)
my_order.has_whip = True
# Add 2 marshmallows using mallow_adder.
my_order.mallow_adder(2)
# Create viktoryas_order with whip, "peppermint" flavor, 10 marshmallows, and sweetness level 2.
viktoryas_order: HotCocoa = HotCocoa(True, "peppermint", 10, 2)
# Calculate the cost of [my_order, viktoryas_order] by calling order_cost.
order_cost([my_order, viktoryas_order])
# Print out the details of my_order.
print(my_order) # or print(str(my_order))
TimeSpent solution
class TimeSpent:
name: str
purpose: str
minutes: int
def __init__(self, name: str, purpose: str, minutes: int):
self.name = name
self.purpose = purpose
self.minutes = minutes
def add_time(self, increase: int) -> None:
self.minutes += increase
def __add__(self, added_minutes: int) -> TimeSpent:
return TimeSpent(self.name, self.purpose, self.minutes + added_minutes)
def reset(self) -> None:
old_value: int = self.minutes
self.minutes = 0
return old_value
def __str__(self) -> str:
minutes: int = self.time % 60
hours: int = (self.time - minutes)/ 60
return f"{self.name} has spent {hours} hours and {minutes} minutes on screen time."
def most_by_purpose(times: list[TimeSpent], activity: str) -> str:
max_time: int = 0
max_name: str = ""
for elem in times:
if (elem.purpose == activity) and (elem.minutes > max_time):
max_time = elem.minutes
max_name = elem.name
return max_name
Magic Methods
Conceptual
Consider the following code snippet:
class Point: x: float y: float def __init__(self, x: float, y: float): self.x = x self.y = y def __str__(self) -> str: return f"({self.x}, {self.y})" def __repr__(self) -> str: return f"Point({self.x}, {self.y})" my_point: Point = Point(1, 2) my_str: str = f"My point is {my_point}!"Would the line of code that creates
my_stralso call thePointclass’s__str__method?In order to call a magic method, you usually use its name (e.g.
__str__) directly just like any other method (T/F).The
__add__method does not modifyself(T/F).What does a
__str__method generally return?For the
Pointclass, what would be the type of a__gt__method’s return value? Is this true for all possible classes that a__gt__method could be defined for?For the
Pointclass, what would be the type of a__add__method’s return value? Is this true for all possible classes that a__add__method could be defined for?
SOLUTIONS
Yes it would! In order to create a
strobject that includesmy_pointlike this in the f-string, the__str__method ofmy_pointis implicitly called.False! It is almost always implicitly called such as in the previous question, or such as when the
__init__method is called using the class name.True! The
__add__method creates a new object without modifying its parameters, includingself.The
__str__returns a human-readable string that represents the object, usually including its attributes.The type would be
bool, and this is true for all possible classes that__gt__could defined for, since it is called when you make an expression using the comparison operator>, so the result must be abool.The type would be
Point, but this is not true for all classes. The return type of__add__for a given class is that class, since__add__is used to create a new object of the same class based on the attributes of the two objects on either side of the+in the expression.
Code-Writing
Consider the following incomplete class definition along with the previously defined
Pointclass:class Rectangle: bottom_left: Point bottom_right: Point top_left: Point top_right: Point def __init__(self, bl: Point, br: Point, tl: Point, tr: Point): self.bottom_left = bl self.bottom_right = br self.top_left = tl self.top_right = tr def area(self) -> int: """Returns the area of the rectangle.""" ... def perimeter(self) -> int: """Returns the perimeter of the rectangle.""" ... def __gt__(self, other: Rectangle) -> bool: """Returns True if self has a larger _____ than other.""" ...1.1. Fill in the methods for area and perimeter using the four
Pointattributes of theRectangleclass.1.2. Fill in the
__gt__method in two ways, first as if the blank in the docstring said “area” and second as if the blank in the docstring said “perimeter”. In both, make sure to use theareaandperimetermethods that you defined (the two implementations of__gt__should look very similar).1.3. (Challenge Question) How could you equivalently write this class definition while using only two attributes? How would your
area,perimetermethods change with only two attributes? Would your__gt__method change (in either case, area or perimeter)?1.4. (Challenge Question) Write a
__str__method forRectanglethat works like in the following example:$ python >>> my_rect: Rectangle = Rectangle(Point(0, 0), Point(1, 0), Point(0, 1), Point(1, 1)) >>> print(my_rect) (0, 1) (1, 1) (0, 0) (1, 0) Area: 1 Perimeter: 4Hint: Use
"\n"to add new lines! Example:$ python >>> print("Hello!\nHello again!") Hello! Hello again!
SOLUTIONS
from __future__ import annotations
# Included for context, and so you can run it yourself!
class Point:
x: float
y: float
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __str__(self) -> str:
return f"({self.x}, {self.y})"
def __repr__(self) -> str:
return f"Point({self.x}, {self.y})"
class Rectangle:
bottom_left: Point
bottom_right: Point
top_left: Point
top_right: Point
def __init__(self, bl: Point, br: Point, tl: Point, tr: Point):
self.bottom_left = bl
self.bottom_right = br
self.top_left = tl
self.top_right = tr
# 1.1
def area(self) -> int:
"""Returns the area of the rectangle."""
x_length: int = self.bottom_right.x - self.bottom_left.x
y_length: int = self.top_left.y - self.bottom_left.y
return x_length * y_length
def perimeter(self) -> int:
"""Returns the perimeter of the rectangle."""
x_length: int = self.bottom_right.x - self.bottom_left.x
y_length: int = self.top_left.y - self.bottom_left.y
return (x_length * 2) + (y_length * 2)
# 1.2
# Note: In a real class definition it would be incorrect to have
# two methods with the same name like this.
def __gt__(self, other: Rectangle) -> bool:
"""Returns True if self has a larger area than other."""
return self.area() > other.area()
def __gt__(self, other: Rectangle) -> bool:
"""Returns True if self has a larger perimeter than other."""
return self.perimeter() > other.perimeter()
# 1.4
def __str__(self) -> str:
return f"{self.top_left} {self.top_right}\n{self.bottom_left} {self.bottom_right}\nArea: {self.area()}\nPerimeter: {self.perimeter()}"For question 1.3, you can represent a rectangle with just two of its opposite corners, since the bottom left’s x coordinate should be the same as it’s top left x coordinate, and the same with the bottom and top right’s x. Similarly, the bottom left’s y coordinate should be the same as the bottom right’s y coordinate, and the same with the top left and top right’s y.
The area and perimeter methods you wrote previously might be the same, but likely are not since the most intuitive way to measure the x and y length of a rectangle would be on the same side. But by the same reasoning as we used to know where the other two corners are, we can calculate the x and y lengths like how it is shown below.
The implementation of __gt__ would not change in either case, since area and perimeter would be the ones that changed but would still work as intended for you to compare the two of them!
class Rectangle:
bottom_left: Point
top_right: Point
def __init__(self, bl: Point, tr: Point):
self.bottom_left = bl
self.top_right = tr
def area(self) -> int:
"""Returns the area of the rectangle."""
x_length: int = self.top_right.x - self.bottom_left.x
y_length: int = self.top_right.y - self.bottom_left.y
return x_length * y_length
def perimeter(self) -> int:
"""Returns the perimeter of the rectangle."""
x_length: int = self.top_right.x - self.bottom_left.x
y_length: int = self.top_right.y - self.bottom_left.y
return (x_length * 2) + (y_length * 2)Recursive Structures
Any questions that reference the Node class are referring to a class defined in the following way:
from __future__ import annotations
class Node:
value: int
next: Node | None
def __init__(self, val: int, next: Node | None):
self.value = val
self.next = next
def __str__(self) -> str:
rest: str
if self.next is None:
rest = "None"
else:
rest = str(self.next)
return f"{self.value} -> {rest}"Multiple Choice
(Select all that apply) Which of the following properties of a recursive function will ensure that it does not have an infinite loop?
The function calls itself in the recursive case.
The recursive case progresses towards the base case.
The base case returns a result directly (it does not call the function again).
The base case is always reached.
None of the above
(Fill in the blank) A linked list in python consists of one or more instances of the _____ class.
listintNodeNoneNone of the above
(True/False) Attempting to access the
valueornextattribute ofNonewill result in an error.(True/False) There is no way to traverse to the start of a linked list that has multiple Nodes given only a reference to the last
Node.
SOLUTIONS
B, C, and D. A is true of all recursive functions, but does not guarantee that there won’t be an infinite loop.
C
True, attempting to access any attributes of
Nonewill result in an error since it has no attributes.True, Nodes only know about the
Node“in front” of them, or the nextNode, so you cannot move backwards in a linked list.
Code Writing
Write a recursive function (not a method of the
Nodeclass) namedrecursive_rangewithstartandendintparameters that will create a linked list with the Nodes having values counting fromstarttoend, not includingend, either counting down (decrementing) or up (incrementing) depending on whatstartandendare. The function signature is below to get you started.def recursive_range(start: int, end: int) -> Node | None:Write a recursive method of the
Nodeclass namedappendthat has parametersselfandnew_valwhich is of typeint, and this method should create a newNodeat the end of the linked list and returnNone. In other words, the lastNodeobject before this method is called will have anextattribute ofNone, but after this method is called, it should have anextattribute equal to aNodeobject with valuenew_valandnextattribute beingNone(since that new node is now the lastNodein the linked list).Write a recursive method of the
Nodeclass namedget_lengththat has parametersselfandcountwhich is of typeint, which if you were to call with acountargument of 0, would return the length of the linked list starting withself(not includingNone). Hint: Usecountto keep track of aNodecount between function calls. How would you write this method as an iterative function (with nocountparameter)?
SOLUTIONS
Recursive range has two base cases, and the one that is used depends on if
startis greater than or less thanend.def recursive_range(start: int, end: int) -> Node | None: if start == end: return None elif start < end: return Node(start, recursive_range(start + 1, end)) else: return Node(start, recursive_range(start - 1, end))Here is one way to make the
appendmethod:def append(self, new_val: int) -> None: if self.next is None: self.next = Node(new_val, None) else: self.next.append(new_val)Here are two possibilities:
def get_length(self, count: int) -> int:
if self.next is None:
return count + 1
else:
return self.next.get_length(count + 1) def get_length(self, count: int) -> int:
count += 1
if self.next is None:
return count
else:
return self.next.get_length(count)Short Answer
Based on the following code snippet, what would be the output of the following lines of code given in parts 1.1-1.4?
from __future__ import annotations # Node class definition included for reference! class Node: value: int next: Node | None def __init__(self, val: int, next: Node | None): self.value = val self.next = next def __str__(self) -> str: rest: str if self.next is None: rest = "None" else: rest = str(self.next) return f"{self.value} -> {rest}" x: Node = Node(4, None) y: Node = Node(8, None) x.next = y z: Node = Node(16, None) z.next = x x = Node(32, None)1.1.
print(z.next.next.value)1.2.
print(y.next)1.3.
print(x)1.4.
print(z)
SOLUTIONS
Question 1 answers:
1.1.
81.2.
None1.3.
32 -> None1.4.
16 -> 4 -> 8 -> None
Unit Tests
General
- How do you create a test function? What identifies the function as a test?
- How do you create a file to write all your unit tests?
- What does the assert statement do?
- Explain the difference between a use case and an edge case. Give an example of both within a function.
- If a function passes all of its associated unit tests, then the function is implemented correctly for all possible inputs (True/False).
Unit Test Writing and Classifying
- Suppose you have the following function, designed to return the index of the first even number in a list.
def find_even(nums: list[int]) -> int:
idx: int = 0
while idx < len(nums):
if nums[idx] % 2 == 0:
return idx
idx += 1
return -1Fill in this unit test with a use case.
def test_find_even_use_case() -> None:
"""Put code here."""- Suppose you have the following function, designed to calculate the sum of the elements in a list.
def sum_numbers(numbers: list[int]) -> int:
if len(numbers) == 0:
raise Exception("Empty list - no elements to add")
total: int = numbers[0]
for i in range(1, len(numbers)):
total += numbers[i]
return totalFill in this unit test with a use case.
def test_list_sum_use_case() -> None:
"""Put code here."""- Suppose you have the following function, designed to determine if a number is prime.
def is_prime(n: int) -> bool:
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return TrueFill in this unit test with a use case.
def test_is_prime_use_case() -> None:
"""Put code here."""- Suppose you want to test that a list of dictionaries will be mutated correctly. Here’s a function that mutates a list of dictionaries by adding a new key-value pair to each dictionary in the list.
def add_key_to_dicts(dicts: list[dict], key: str, value: int) -> None:
for d in dicts:
d[key] = valueFill in this unit test with a use case to verify that the list of dictionaries is mutated correctly.
def test_add_key_to_dicts_use_case() -> None:
"""Put code here."""- Suppose you want to test that a dictionary will be mutated correctly. Here’s a function that mutates a dictionary by incrementing the value of a given key by 1.
def increment_dict_value(d: dict[str, int], key: str) -> None:
if key in d:
d[key] += 1
else:
d[key] = 1Fill in this unit test with a use case to verify that the dictionary is mutated correctly.
def test_increment_dict_value_use_case() -> None:
"""Put code here."""- Suppose you have the following function, designed to sum the elements in a dictionary of list values and return the key with the largest summed value.
def max_sum_dict(d: dict[str, list[int]]) -> str:
keys = []
for key in d:
keys.append(key)
values_list_1 = d[keys[0]]
values_list_2 = d[keys[1]]
total_1 = 0
for value in values_list_1:
total_1 += value
total_2 = 0
for value in values_list_2:
total_2 += value
if total_1 > total_2:
return keys[0]
else:
return keys[1]Fill in this unit test with a use case to verify that the function returns the key with the largest summed value.
def test_max_sum_dict_use_case() -> None:
"""Put code here."""- Write three unit tests for the following function, two testing use cases and one testing an edge case.
def divide_list(input_list: list[int], divisor: int) -> list[float]:
"""Returns a new list where each value is the value from input_list divided by divisor"""
result: list[int] = []
for num in input_list:
result.append(num / divisor)
return result- Consider the following code snippet:
def fill_list(num: int, length: int) -> list[int]:
"""Fill a list with a single value."""
result: list[int] = []
i: int = 0
while i < length:
result.append[num]
i += 1
return result
list_A: list[int] = fill_list(4, 19)
list_B: list[int] = fill_list(55, -2)
list_C: list[int] = fill_list(1, 110)Which function calls would be considered a use case of this function (list the associated variable name e.g. list_A)? Which would be considered edge cases? If there are any edge cases, what result would you get in the associated variable(s)?
SOLUTIONS
Question 1 answers:
1.1.
81.2.
None1.3.
32 -> None1.4.
16 -> 4 -> 8 -> None
Conceptual Solutions
A test function is created just like any other Python function, but it is identified as a test by starting its name with
test_. In frameworks like pytest, any function that starts withtest_is automatically detected and run as a test.Create a new Python file, often named
<module_name>_test.py, in the same directory as your module. Write all your test functions in this file.The assert statement checks if a condition is true. If the condition is false, an AssertionError is raised, indicating that the test has failed.
A use case is a typical scenario where the function is expected to work as intended. For example, in a function that sums a list, a use case would be passing a list like
[1, 2, 3]. An edge case is a situation where the function might struggle or behave differently, like passing an empty list[]to a sum function.This is False, as unit tests themselves can be incorrect so all tests passing is no guarantee of correctness even for the inputs the unit tests are testing for. Even if the unit tests are correct, there can still be certain inputs that they do not test for and therefore the unit tests cannot assure you that a function will always work properly. Unit tests are a helpful tool that can work well when implemented over a wide range of test inputs, but they must be accompanied by thoughtful implementation of the original function.
Unit Test Writing
- Solution below:
def test_find_even_use_case() -> None:
nums = [1, 3, 5, 4, 7]
assert find_even(nums) == 3- Solution below:
def test_list_sum_use_case() -> None:
# Test case 1: Normal list of positive numbers
assert sum_numbers([1, 2, 3, 4, 5]) == 15
# Test case 2: List with negative numbers
assert sum_numbers([-1, -2, -3, -4, -5]) == -15
# Test case 3: Mixed positive and negative numbers
assert sum_numbers([1, -1, 2, -2, 3, -3]) == 0
# Test case 4: List with a single element
assert sum_numbers([10]) == 10
# Do not worry about handling the exception!
# That is out of the scope of the class :)- Solution below:
def test_is_prime_use_case() -> None:
assert is_prime(7) is True
assert is_prime(8) is False- Solution below:
def test_add_key_to_dicts_use_case() -> None:
dicts = [{"a": 1}, {"b": 2}]
add_key_to_dicts(dicts, "c", 3)
assert dicts == [{"a": 1, "c": 3}, {"b": 2, "c": 3}]- Solution below:
def test_increment_dict_value_use_case() -> None:
d = {"a": 1, "b": 2}
increment_dict_value(d, "a")
assert d["a"] == 2
increment_dict_value(d, "c")
assert d["c"] == 1- Solution below:
def test_max_sum_dict_use_case() -> None:
d = {"a": [1, 2, 3], "b": [4, 5]}
assert max_sum_dict(d) == "b"list_Aandlist_Cwould be use cases since this is how we would expect this function to be used andlist_Bwould be an edge case as this is essentially attempting to make a function call that would construct a list of negative length since ourlengthargument is -2. In this edge case the result would be an empty list since we would never enter thewhileloop.Note: These are just some examples of what you could test for, but they will likely not be the same as what you wrote as there are many correct answers.
The most straightforward use case test would be ensuring that on a normal input that the output is what you expect:
def test_normal_divide_list() -> None: classes: list[int] = [110, 210, 301, 455] assert divide_list(classes, 10) = [11.0, 21.0, 30.1, 45.5]Another unit test for an edge case might be to ensure that the original list was not mutated:
def test_no_mutate_divide_list() -> None: classes: list[int] = [110, 210, 301, 455] divide_list(classes, 10) # We don't need to store the result assert classes = [110, 210, 301, 455]Finally, an example of an edge case for this function would be a divisor of zero, which we should expect to result in an error. We can test to ensure that an error occurs like this:
def test_div_zero_error_divide_list() -> None: classes: list[int] = [110, 210, 301, 455] with pytest.raises(ZeroDivisionError): divide_list(classes, 0)