Advertisement
gauravssnl

ShoppingCart.py

Feb 24th, 2017
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.16 KB | None | 0 0
  1. # ShoppingCart.py by gauravssnl
  2.  
  3. class ShoppingCart :
  4.     def __init__( self ) :
  5.         self.total = 0
  6.         self.items = { }
  7.    
  8.     def add_item( self , item_name , quantity , price ) :
  9.         self.total += quantity* price
  10.         # set dictionary key to item_name and value to quantity
  11.         self.items[ item_name ] = quantity
  12.        
  13.     def remove_item( self , item_name , quantity , price ) :
  14.         if quantity > self.items[ item_name ] :
  15.             self.total -= self.items[ item_name ] * price
  16.             del self.items[item_name]
  17.         else :
  18.             self.total -= quantity * price
  19.             self.items[ item_name ] -= quantity
  20.    
  21.     def checkout( self , cash_paid ) :
  22.         if cash_paid >= self.total :
  23.             return  cash_paid - self.total
  24.         else :
  25.             return "Cash paid not enough"
  26.        
  27.  
  28. class Shop( ShoppingCart ) :
  29.     def __init__( self ) :
  30.         self.quantity = 100
  31.    
  32.     def remove_item(self ,quantity = 1 ) :
  33.         self.quantity -= quantity
  34.  
  35. if __name__ == '__main__' :
  36.     sc = ShoppingCart()
  37.    
  38.     # to check class attributes and to ensure methods are working correctly , we are printing them
  39.     # printing attributes are optional
  40.    
  41.     # first argument is quantity ,second argument is price
  42.     # add 50 items whose price is 30
  43.     sc.add_item( 'NoteBook' , 50 , 30 )
  44.     print( sc.items )
  45.     print( sc.items['NoteBook'] )
  46.     print( sc.total )
  47.     #cash_paid is 2000 and is more than 1500 (50*30)
  48.     print ( 'Balance : ')
  49.     print( sc.checkout( 2000 ))
  50.    
  51.     # remove 10 items whose price is 30
  52.     sc.remove_item('NoteBook' , 10 , 30)
  53.     print( sc.items )
  54.     print( sc.items['NoteBook'] )
  55.     print( sc.total )
  56.    
  57.     #cash_paid is 1000 and Less than 1200 (40*30)
  58.    
  59.     print( sc.checkout(1000 ))
  60.     # remove 41 items whose price is 30
  61.     #item being removed is more than existing items ,so item NoteBook will be removed from dictionary
  62.     sc.remove_item('NoteBook' , 41 , 30)
  63.     print( sc.items )
  64.    
  65.     print( sc.total )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement