Advertisement
furas

Python - ShoppingCart

Feb 28th, 2017
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.65 KB | None | 0 0
  1. class ShoppingCart:
  2.    
  3.     def __init__(self):
  4.         self.total = 0
  5.         self.items = dict()
  6.         #self.items = {}
  7.  
  8.     def add_item(self, item_name, quantity, price):
  9.         self.total += quantity*price
  10.        
  11.         if item_name not in self.items:
  12.             self.items[item_name] = quantity
  13.         else:
  14.             self.items[item_name] += quantity
  15.  
  16. # ---- test ----
  17.  
  18. cart = ShoppingCart()
  19.  
  20. cart.add_item('banana', 3, 4)
  21. cart.add_item('banana', 5, 4) # add againg the same item
  22. cart.add_item('orange', 2, 3)
  23.  
  24. print('total:', cart.total)
  25. print('items:', cart.items)
  26.  
  27. # total: 38
  28. # items: {'orange': 2, 'banana': 8}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement