Bird
Raised Fist0
Pythonprogramming~20 mins

Real-world modeling using objects in Python - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Object Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of method calls on a class instance

Consider the following Python class modeling a simple bank account. What will be the output after running the code?

Python
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance
    
    def deposit(self, amount):
        self.balance += amount
        return self.balance
    
    def withdraw(self, amount):
        if amount > self.balance:
            return "Insufficient funds"
        self.balance -= amount
        return self.balance

account = BankAccount("Alice", 100)
print(account.deposit(50))
print(account.withdraw(30))
print(account.withdraw(150))
A
100
50
Insufficient funds
B
150
70
Insufficient funds
C
150
70
-50
D
150
120
Insufficient funds
Attempts:
2 left
💡 Hint

Think about how the balance changes after each method call.

🧠 Conceptual
intermediate
1:30remaining
Understanding object attributes and methods

Which statement about Python objects is correct?

AAn object's methods can only access variables defined inside the method itself.
BEach object instance has its own copy of instance variables.
CInstance variables are shared across all instances of a class.
DClass variables are unique to each object instance.
Attempts:
2 left
💡 Hint

Think about what happens when you create multiple objects from the same class.

Predict Output
advanced
2:30remaining
Output of inheritance and method overriding

What will be printed when the following code runs?

Python
class Vehicle:
    def __init__(self, brand):
        self.brand = brand
    def start(self):
        return f"{self.brand} vehicle started"

class Car(Vehicle):
    def start(self):
        return f"{self.brand} car started with key"

class ElectricCar(Car):
    def start(self):
        return f"{self.brand} electric car started silently"

v = Vehicle("Generic")
c = Car("Toyota")
e = ElectricCar("Tesla")
print(v.start())
print(c.start())
print(e.start())
A
Generic vehicle started
Toyota car started with key
Tesla electric car started silently
B
Generic vehicle started
Toyota vehicle started
Tesla car started with key
C
Generic vehicle started
Toyota car started with key
Tesla vehicle started
D
Generic vehicle started
Toyota electric car started silently
Tesla electric car started silently
Attempts:
2 left
💡 Hint

Look at how each class overrides the start method.

🔧 Debug
advanced
1:30remaining
Identify the error in object initialization

What error will this code produce when run?

Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Bob")
ATypeError: __init__() missing 1 required positional argument: 'age'
BNameError: name 'age' is not defined
CAttributeError: 'Person' object has no attribute 'age'
DNo error, object created successfully
Attempts:
2 left
💡 Hint

Check how many arguments the constructor expects versus how many are given.

🚀 Application
expert
3:00remaining
Calculate total price with object composition

Given the classes below modeling products and a shopping cart, what is the output of the final print statement?

Python
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

class ShoppingCart:
    def __init__(self):
        self.items = []
    
    def add_product(self, product, quantity):
        self.items.append((product, quantity))
    
    def total_price(self):
        total = 0
        for product, quantity in self.items:
            total += product.price * quantity
        return total

p1 = Product("Book", 12.99)
p2 = Product("Pen", 1.50)
cart = ShoppingCart()
cart.add_product(p1, 3)
cart.add_product(p2, 10)
print(f"Total: ${cart.total_price():.2f}")
ATotal: $51.99
BTotal: $49.47
CTotal: $53.97
DTotal: $60.00
Attempts:
2 left
💡 Hint

Multiply each product's price by its quantity and add all together.

Practice

(1/5)
1. Which of the following best describes an object in Python when modeling real-world things?
easy
A. An object is just a list of numbers used for calculations.
B. An object is a special keyword used to start a program.
C. An object is a type of function that runs automatically.
D. An object is a combination of data (attributes) and actions (methods) representing something real.

Solution

  1. Step 1: Understand what an object represents

    An object models real-world things by holding data and actions together.
  2. Step 2: Compare options with this understanding

    Only An object is a combination of data (attributes) and actions (methods) representing something real. correctly describes an object as data plus actions representing something real.
  3. Final Answer:

    An object is a combination of data (attributes) and actions (methods) representing something real. -> Option D
  4. Quick Check:

    Object = Data + Actions [OK]
Hint: Objects combine data and actions like real things [OK]
Common Mistakes:
  • Thinking objects are just lists or numbers
  • Confusing objects with functions
  • Believing objects are keywords
2. Which of the following is the correct way to define a simple class named Car in Python?
easy
A. class Car()
B. class Car: pass
C. def Car: pass
D. Car = class()

Solution

  1. Step 1: Recall Python class syntax

    Classes start with the keyword class, followed by the class name and a colon.
  2. Step 2: Check each option

    class Car: pass correctly uses class Car: and a body with pass. Others have syntax errors.
  3. Final Answer:

    class Car:\n pass -> Option B
  4. Quick Check:

    class keyword + name + colon = correct class [OK]
Hint: Use 'class ClassName:' to define a class [OK]
Common Mistakes:
  • Using def instead of class
  • Missing colon after class name
  • Trying to assign class to a variable
3. What will be the output of this code?
class Dog:
    def __init__(self, name):
        self.name = name
    def bark(self):
        return f"{self.name} says Woof!"

my_dog = Dog('Buddy')
print(my_dog.bark())
medium
A. my_dog says Woof!
B. Woof!
C. Buddy says Woof!
D. Error: missing self parameter

Solution

  1. Step 1: Understand the class and method

    The Dog class stores the dog's name and the bark method returns a string with the dog's name.
  2. Step 2: Trace the code execution

    Creating my_dog = Dog('Buddy') sets self.name to 'Buddy'. Calling my_dog.bark() returns 'Buddy says Woof!'.
  3. Final Answer:

    Buddy says Woof! -> Option C
  4. Quick Check:

    Method uses self.name = Buddy [OK]
Hint: Methods use self to access object data [OK]
Common Mistakes:
  • Ignoring self and expecting just 'Woof!'
  • Printing variable name instead of value
  • Confusing method call syntax
4. Find the error in this class definition and choose the correct fix:
class Book:
    def __init__(title, author):
        self.title = title
        self.author = author
medium
A. Add 'self' as the first parameter in __init__ method.
B. Change __init__ to init without underscores.
C. Remove self from inside the method.
D. Rename class to book (lowercase).

Solution

  1. Step 1: Identify the __init__ method parameters

    The first parameter of any instance method must be self to refer to the object.
  2. Step 2: Check the given code

    The __init__ method lacks self as the first parameter, causing an error when assigning attributes.
  3. Final Answer:

    Add 'self' as the first parameter in __init__ method. -> Option A
  4. Quick Check:

    Instance methods need self first [OK]
Hint: Always put self as first method parameter [OK]
Common Mistakes:
  • Forgetting self in method parameters
  • Changing __init__ name incorrectly
  • Ignoring case sensitivity in class names
5. You want to model a Library that holds many Book objects. Which design best uses classes to represent this real-world situation?
hard
A. Create a Book class with title and author, and a Library class with a list of Book objects as an attribute.
B. Create only a Library class with title and author attributes.
C. Create a Book class with a list of libraries it belongs to, no Library class.
D. Use a single class named BookLibrary with no separate classes.

Solution

  1. Step 1: Understand the real-world relationship

    A library contains many books, so it makes sense to have separate classes for each.
  2. Step 2: Check which design models this well

    Create a Book class with title and author, and a Library class with a list of Book objects as an attribute. uses a Book class for individual books and a Library class holding a list of books, matching the real-world model.
  3. Final Answer:

    Create a Book class with title and author, and a Library class with a list of Book objects as an attribute. -> Option A
  4. Quick Check:

    Separate classes + composition = best model [OK]
Hint: Use separate classes and lists to model collections [OK]
Common Mistakes:
  • Combining unrelated data in one class
  • Ignoring relationships between objects
  • Not using lists to hold multiple objects