Consider the following Python class modeling a simple bank account. What will be the output after running the code?
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))
Think about how the balance changes after each method call.
The initial balance is 100. Deposit adds 50, so balance becomes 150. Withdraw 30 reduces balance to 120. Withdraw 150 is more than balance, so it returns "Insufficient funds".
Which statement about Python objects is correct?
Think about what happens when you create multiple objects from the same class.
Instance variables belong to each object separately. Class variables are shared by all instances.
What will be printed when the following code runs?
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())
Look at how each class overrides the start method.
Each subclass overrides the start method to provide its own message. The calls print the overridden versions.
What error will this code produce when run?
class Person: def __init__(self, name, age): self.name = name self.age = age p = Person("Bob")
Check how many arguments the constructor expects versus how many are given.
The constructor requires two arguments: name and age. Only one was provided, so Python raises a TypeError.
Given the classes below modeling products and a shopping cart, what is the output of the final print statement?
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}")
Multiply each product's price by its quantity and add all together.
Book: 12.99 * 3 = 38.97; Pen: 1.50 * 10 = 15.00; Total = 38.97 + 15.00 = 53.97