Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ShoppingCart:
- def __init__ (self):
- self.total = 0
- self.items = {}
- def add_item(self, item_name, quantity, price):
- self.total += quantity * price
- self.items[item_name] = quantity
- def remove_item(self, item_name, quantity, price):
- if quantity > self.items[item_name]:
- quantity = self.items[item_name]
- self.total -= quantity * price
- self.items[item_name] -= quantity
- def checkout(self, cash_paid):
- if cash_paid < self.total:
- return "Cash paid not enough"
- balance = cash_paid - self.total
- return balance
- # --- test ---
- a = ShoppingCart()
- print('\n--- adding items ---\n')
- a.add_item('banana', 5, 4)
- a.add_item('orange', 3, 5)
- print('total:', a.total)
- print('items:', a.items)
- print('\n--- removing 6 bananas ---\n')
- a.remove_item('banana', 6, 4)
- print('total:', a.total)
- print('items:', a.items)
- print('\n--- removing 3 bananas ---\n')
- a.remove_item('banana', 3, 4)
- print('total:', a.total)
- print('items:', a.items)
- print('\n--- checkout ---\n')
- print('result:', a.checkout(10))
- print('result:', a.checkout(50))
- '''
- --- adding items ---
- total: 35
- items: {'banana': 5, 'orange': 3}
- --- removing 6 bananas ---
- total: 15
- items: {'banana': 0, 'orange': 3}
- --- removing 3 bananas ---
- total: 15
- items: {'banana': 0, 'orange': 3}
- --- checkout ---
- result: Cash paid not enough
- result: 35
- '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement