Python, Concept by Concept › Objects

Exercises: Objects

Core work is Exercises 1–10. Exercises 11–20 are More Practice; Exercises 21–24 are optional Challenges. Define each requested class or function with the exact name and parameters. Keep every file exercise self-contained: write its named scratch file before reading it. The real programs read values with input(), build the objects, and print the answers.

For every exercise, try all worked sample calls. Methods that calculate an answer must return it. Use self for THIS particular object's attributes, and add a short purpose comment.

Exercise 1: Two Separate Points

A map needs two markers that can change independently.

Specification: Define Point with __init__(self, x, y) and store both parameters as attributes. Make start = Point(2, 6) and finish = Point(9, 4). Change only start.x to 5. Read and print both objects' x attributes to prove that finish.x is untouched.

Worked sample reads:

start.x  -> 5
start.y  -> 6
finish.x -> 9
finish.y -> 4

Real program

The real program reads the two points’ coordinates and the replacement start.x value with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 2: Rectangle Record

A sign shop needs each order to carry its code, width, and height together.

Specification: Define Rectangle with __init__(self, code, width, height). Store all three parameters as attributes. Make two rectangles with the sample values and read their attributes.

Worked sample calls and reads:

small = Rectangle("N-12", 6, 4)
large = Rectangle("S-30", 12, 7)
small.code   -> "N-12"
small.width  -> 6
large.height -> 7

Real program

The real program reads two rectangles’ codes, widths, and heights with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 3: Rectangle Measurements

The sign shop wants each rectangle to calculate its own measurements.

Specification: Define Rectangle with __init__(self, width, height) and store width and height as attributes. Add area(self) and perimeter(self) methods. Each method must use the object's attributes and return a number.

Worked sample calls:

tile = Rectangle(9, 4)
tile.area()      -> 36
tile.perimeter() -> 26
Rectangle(2.5, 6).area() -> 15.0

Real program

The real program reads two rectangles’ widths and heights with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 4: Distance Between Points

A route planner needs one point to measure its straight-line distance to another point.

Specification: Define Point with x and y attributes. Add distance(self, other). Compute dx and dy, then return (dx * dx + dy * dy) ** 0.5. Do not import a square-root tool.

Worked sample calls:

Point(1, 2).distance(Point(4, 6)) -> 5.0
Point(2, 1).distance(Point(2, 6)) -> 5.0
Point(1, 1).distance(Point(1, 1)) -> 0.0

Real program

The real program reads three pairs of points’ coordinates with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 5: Short Code and Description

A warehouse display needs a short region code and a readable rectangle description.

Specification: Define Rectangle with code, width, and height attributes. Add short_code(self) that returns the genuine attribute slice self.code[0:2]. Add describe(self) that returns an f-string in the form "code: width by height".

Worked sample calls:

crate = Rectangle("NE-48", 7, 3)
crate.short_code() -> "NE"
crate.describe()   -> "NE-48: 7 by 3"
Rectangle("SW-9", 2, 2).short_code() -> "SW"

Real program

The real program reads two rectangles’ codes, widths, and heights with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 6: Score Counter

A game needs a counter that remembers its label and changing count.

Specification: Define Counter with __init__(self, label). Store the label and start count at 0. Add increment(self, amount) that adds amount to self.count and returns the new count. Make two counters and change only one of them.

Worked sample calls and reads:

blue = Counter("blue")
gold = Counter("gold")
blue.increment(3) -> 3
blue.increment(2) -> 5
blue.count        -> 5
gold.count        -> 0

Real program

The real program reads two counter labels and two increment amounts with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 7: Save and Load a Point

A map editor needs to rebuild a point after the program ends.

Specification: Define Point with x and y attributes plus save(self, path). The method must open path in "w" mode, write each attribute on its own f-string line, then return path. Define a separate module-level function load_point(path). It must open path in explicit "r" mode, use readline(), .strip(), and int() to rebuild both values, then return a new Point.

Use only ex7_point.txt. In the same cell, make and save the point before you load it, so the exercise is self-contained.

Worked sample calls and reads:

original = Point(14, 9)
original.save("ex7_point.txt") -> "ex7_point.txt"
loaded = load_point("ex7_point.txt")
loaded.x -> 14
loaded.y -> 9

Real program

The real program reads the point coordinates with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 8: Draw a Rectangle

A sign maker wants a rectangle drawn with number signs.

Specification: Define Rectangle with __init__(self, width, height) and draw(self). Add a short purpose comment. Store the dimensions. In draw, append one "#" * self.width row for each unit of height, then return "\n".join(rows). Do not leave trailing spaces.

Worked sample calls:

Rectangle(4, 2).draw() -> "####\n####"

Real program

The real program reads the rectangle width and height with input().

How this is checked: Checked by tests that run your function Rectangle.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 9: Bank Account

An account owner needs deposits and withdrawals to change one balance.

Specification: Define BankAccount with __init__(self, owner, balance), deposit(self, amount), and withdraw(self, amount). Add a short purpose comment. Store owner and balance. A deposit adds the amount and returns the balance. If a withdrawal is larger than the balance, return "Insufficient funds" without changing it; otherwise subtract the amount and return the balance.

Worked sample calls:

account = BankAccount("Idris", 50)
account.deposit(30) -> 80
account.withdraw(100) -> "Insufficient funds"
account.balance -> 80
account.withdraw(25) -> 55

Real program

The real program reads the owner, starting balance, deposit amount, and two withdrawal amounts with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 10: Traffic Light

A crossing signal cycles through three colors.

Specification: Define TrafficLight with __init__(self) that starts self.state at "green" and next(self) that changes the state using an if/elif/else chain: green to yellow, yellow to red, red to green. Add a short purpose comment. Return the new state.

Worked sample calls:

light = TrafficLight()
light.state -> "green"
light.next() -> "yellow"
light.next() -> "red"
light.next() -> "green"

Real program

The real program reads the number of light changes to make with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 11: More Practice: Playlist

A music player keeps songs in the order they were added.

Specification: Define Playlist with __init__(self), a list attribute self.songs, add(self, title) that appends a title, and song_count(self) that returns the list length.

Worked sample calls:

playlist = Playlist()
playlist.add("Tide")
playlist.add("Ember")
playlist.song_count() -> 2
playlist.songs -> ["Tide", "Ember"]

Real program

The real program reads the number of songs and each song title with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 12: More Practice: Vending Machine

A vending machine collects credit until it can release an item.

Specification: Define VendingMachine with __init__(self, price) and insert(self, amount). Start credit at 0. Each insert adds to credit. If credit is less than price, return an f-string "Insert N more" with the remaining amount. Otherwise return an f-string "Vend! Change: N" with the change and reset credit to 0.

Worked sample calls:

machine = VendingMachine(3)
machine.insert(1) -> "Insert 2 more"
machine.insert(1) -> "Insert 1 more"
machine.insert(2) -> "Vend! Change: 1"
machine.credit -> 0

Real program

The real program reads the price, number of insertions, and each inserted amount with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 13: More Practice: Stockroom

A workshop tracks quantities by item name.

Specification: Define Stockroom with dictionary attribute self.stock = {}. add(self, name, amount) uses if name in self.stock to increase an existing quantity or stores amount for a new name. remove(self, name, amount) subtracts the amount.

Worked sample calls:

room = Stockroom()
room.add("rivet", 10)
room.add("washer", 4)
room.remove("rivet", 3)
room.stock -> {"rivet": 7, "washer": 4}

Real program

The real program reads the number of stock changes and each action, item name, and amount with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 14: More Practice: Student Grades

A student record collects scores before calculating an average.

Specification: Define Student with __init__(self, name), list attribute self.scores, add_score(self, score) that appends, and average(self) that returns sum(self.scores) / len(self.scores). Assume at least one score before averaging.

Worked sample calls:

student = Student("Yusra")
student.add_score(80)
student.add_score(90)
student.average() -> 85.0

Real program

The real program reads the student name, number of scores, and each score with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 15: More Practice: Game Board

A board game needs a blank grid and a text picture of its current pieces.

Specification: Define GameBoard with __init__(self, size) that builds self.cells as a size-by-size list of lists containing "."; build each row with append, then append each row. place(self, row, col, mark) writes one cell. render(self) loops over rows, joins each row with "".join(row), appends each text row, and returns "\n".join(rows).

Worked sample calls:

board = GameBoard(3)
board.place(0, 0, "X")
board.place(2, 2, "O")
board.render() -> "X..\n...\n..O"

Real program

The real program reads the board size, number of pieces, and each piece’s row, column, and mark with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 16: More Practice: Total Area

A builder wants the combined area of several rectangles.

Specification: Define Rectangle with __init__(self, width, height) and area(self). Define total_area(rectangles) that loops over a list of Rectangle objects, adds each area() to a running total, and returns that total.

Worked sample calls:

total_area([Rectangle(2, 3), Rectangle(4, 5)]) -> 26

Real program

The real program reads the number of rectangles and each width and height with input().

How this is checked: Checked by tests that run your functions total_area, Rectangle.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 17: More Practice: Closest Point

A navigator needs the nearest point from a list of candidates.

Specification: Define Point with x, y, and distance(self, other) using (dx * dx + dy * dy) ** 0.5. Define closest(origin, points) for a nonempty list: start with the first point as best, replace it only when another distance is strictly smaller, and return the Point object. Print the result as f"{best.x} {best.y}".

Worked sample calls:

best = closest(Point(0, 0), [Point(3, 4), Point(1, 1), Point(6, 8)])
print(f"{best.x} {best.y}") -> 1 1

Real program

The real program reads the origin coordinates, number of candidates, and each candidate’s coordinates with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 18: More Practice: Fix the Missing self

A method call fails before it can calculate an area.

Specification: Study the broken code and the exact error. Define a repaired Rect with __init__(self, width, height) and area(self) that returns width times height.

class Rect:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area():
        return self.width * self.height

print(Rect(3, 4).area())

TypeError: Rect.area() takes 0 positional arguments but 1 was given

Worked sample calls:

Rect(3, 4).area() -> 12

How this is checked: Checked by tests that run your function Rect.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 19: More Practice: Fix the Attribute Typo

A crate has the right dimensions, but one attribute name is misspelled.

Specification: Study the broken code and the exact error. Define a repaired Crate whose volume(self) returns width times height times depth.

class Crate:
    def __init__(self, width, height, depth):
        self.width = width
        self.hieght = height
        self.depth = depth

    def volume(self):
        return self.width * self.height * self.depth

print(Crate(2, 3, 4).volume())

AttributeError: 'Crate' object has no attribute 'height'

Worked sample calls:

Crate(2, 3, 4).volume() -> 24

How this is checked: Checked by tests that run your function Crate.

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 20: More Practice: Predict Two Counters

Two objects start with the same label but keep separate counts.

Specification: Predict the exact output of the code. Then define Counter with increment(self, amount) as shown and trace the two objects.

class Counter:
    def __init__(self, label):
        self.label = label
        self.count = 0

    def increment(self, amount):
        self.count = self.count + amount
        return self.count

a = Counter("x")
b = Counter("x")
b.increment(5)
print(a.count, b.count)

Worked sample calls:

print(a.count, b.count) -> 0 5

Starter (read-only)

# Define Counter, trace both objects, then predict the printed line.

How this is checked: Checked by comparing your prediction with what the program really prints.

Answer format: one line

Also check yourself

The automatic check cannot see these, so tick each one when your work does it.

For parents and teachers: report a problem

Exercise 21: Rectangle Size Band

  • Challenge

A shipping system labels rectangles by area.

Specification: Define Rectangle with __init__(self, width, height) and store width and height as attributes. Add area(self). Add size_band(self) that calls self.area() and returns "large" when the area is at least 60, "medium" when the area is at least 25, and "small" otherwise. Use one if/elif/else ladder.

Worked sample calls:

Rectangle(10, 7).size_band() -> "large"
Rectangle(7, 5).size_band()  -> "medium"
Rectangle(4, 3).size_band()  -> "small"

Real program

The real program reads three rectangles’ widths and heights with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 22: Counter Snapshot

  • Challenge

A museum wants to save a visitor counter and rebuild it tomorrow.

Specification: Define Counter with __init__(self, label, count) and store label and count as attributes. Add increment(self, amount) and save(self, path). The save method writes the label and count as two f-string lines. Define a module-level load_counter(path) that opens the file in explicit "r" mode and returns a new Counter with both saved attributes.

Use only ex22_counter.txt. Save before loading in the same cell.

Worked sample calls and reads:

visitors = Counter("north gate", 12)
visitors.increment(4) -> 16
visitors.save("ex22_counter.txt") -> "ex22_counter.txt"
restored = load_counter("ex22_counter.txt")
restored.label -> "north gate"
restored.count -> 16

Real program

The real program reads the counter label, starting count, and increment amount with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 23: Rover Commands

  • Challenge

A rover moves across a grid while facing one of four compass directions.

Specification: Define Rover starting at (0, 0) facing "N". Define run(self, commands) to read each F, R, or L. For right turns use "NESW"[("NESW".find(self.facing) + 1) % 4]; for left use the same index with - 1. F moves one step in the current direction. Use an if/elif/else chain. Define position(self) that returns f"({self.x}, {self.y}) facing {self.facing}".

Worked sample calls:

rover = Rover()
rover.run("FFRFF")
rover.position() -> "(2, 2) facing E"

Real program

The real program reads the command string with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Exercise 24: Save the Stockroom

  • Challenge

A workshop wants to restore tomorrow’s inventory from a saved file.

Specification: Define Stockroom with dictionary attribute stock and add(self, name, amount) using membership for an existing name. Define save(self, path) to write each name,qty record on its own line in explicit "w" mode and return path. Define module-level load_stockroom(path) to read the file in explicit "r" mode, split each stripped line at ",", convert the quantity with int, and rebuild a Stockroom. Save before loading. Use ex24_stockroom.txt.

Worked sample calls:

room = Stockroom()
room.add("rivet", 10)
room.add("washer", 4)
room.stock["rivet"] = 7
room.save("ex24_stockroom.txt") -> "ex24_stockroom.txt"
loaded = load_stockroom("ex24_stockroom.txt")
loaded.stock -> {"rivet": 7, "washer": 4}

Real program

The real program reads the number of item records, then each item name and quantity with input().

How this is checked: You check this one yourself, against the list below.

The site cannot check this one. Run your program, then tick each item below when your work does it.

Check your work

For parents and teachers: report a problem

Back to Objects