class Item:
"""A product in the school store."""
def __init__(self, name, price, stock):
self.name = name
self.price = price # dollars
self.stock = stock # units on hand, never negative
def sell(self, qty):
"""Remove qty units if available; return True if the sale happened."""
if 0 < qty <= self.stock:
self.stock -= qty
return True
return False
def restock(self, qty):
"""Add qty (> 0) units."""
self.stock += qty
def value(self):
"""Return the value of the stock on hand."""
return self.price * self.stock
def __str__(self):
return f"{self.name}: {self.stock} @ ${self.price:.2f}"
store = [Item("Toque", 15.00, 17), Item("Mitts", 12.50, 4),
Item("Scarf", 18.00, 0), Item("Water bottle", 9.75, 30)]
orders = [("Mitts", 3), ("Scarf", 1), ("Toque", 2), ("Hoodie", 1)]
for name, qty in orders:
match = next((it for it in store if it.name == name), None)
if match is None:
print("No such item:", name)
elif not match.sell(qty):
print("Not enough", name)
for it in store:
print(it)
print(f"Total value: ${sum(it.value() for it in store):.2f}")
low = [it.name for it in store if it.stock < 5]
print("Reorder:", low)
A one-dimensional list of objects. The loop finds each ordered item with a linear search (next returns the first match or None) and asks the object to sell itself. The store code never changes stock directly. Output, line by line: Not enough Scarf | No such item: Hoodie | Toque: 15 @ $15.00 | Mitts: 1 @ $12.50 | Scarf: 0 @ $18.00 | Water bottle: 30 @ $9.75 | Total value: $530.00 | Reorder: ['Mitts', 'Scarf']