Advertisement
furas

Python - ShoppingCart

Feb 28th, 2017
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. class ShoppingCart:
  2.    
  3.     def __init__ (self):    
  4.         self.total = 0
  5.         self.items = {}
  6.  
  7.     def add_item(self, item_name, quantity, price):
  8.         self.total += quantity * price
  9.         self.items[item_name] = quantity
  10.  
  11.     def remove_item(self, item_name, quantity, price):
  12.         if quantity > self.items[item_name]:
  13.             quantity = self.items[item_name]
  14.  
  15.         self.total -= quantity * price
  16.         self.items[item_name] -= quantity
  17.  
  18.     def checkout(self, cash_paid):
  19.         if cash_paid < self.total:
  20.             return "Cash paid not enough"
  21.  
  22.         balance = cash_paid - self.total
  23.  
  24.         return balance
  25.  
  26. # --- test ---
  27.  
  28. a = ShoppingCart()
  29.  
  30. print('\n--- adding items ---\n')
  31.  
  32. a.add_item('banana', 5, 4)
  33. a.add_item('orange', 3, 5)
  34.  
  35. print('total:', a.total)
  36. print('items:', a.items)
  37.  
  38. print('\n--- removing 6 bananas ---\n')
  39.  
  40. a.remove_item('banana', 6, 4)
  41.  
  42. print('total:', a.total)
  43. print('items:', a.items)
  44.  
  45. print('\n--- removing 3 bananas ---\n')
  46.  
  47. a.remove_item('banana', 3, 4)
  48.  
  49. print('total:', a.total)
  50. print('items:', a.items)
  51.  
  52. print('\n--- checkout ---\n')
  53.  
  54. print('result:', a.checkout(10))
  55. print('result:', a.checkout(50))
  56.  
  57. '''
  58. --- adding items ---
  59.  
  60. total: 35
  61. items: {'banana': 5, 'orange': 3}
  62.  
  63. --- removing 6 bananas ---
  64.  
  65. total: 15
  66. items: {'banana': 0, 'orange': 3}
  67.  
  68. --- removing 3 bananas ---
  69.  
  70. total: 15
  71. items: {'banana': 0, 'orange': 3}
  72.  
  73. --- checkout ---
  74.  
  75. result: Cash paid not enough
  76. result: 35
  77. '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement