Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ShoppingCart.py by gauravssnl
- class ShoppingCart :
- def __init__( self ) :
- self.total = 0
- self.items = { }
- def add_item( self , item_name , quantity , price ) :
- self.total += quantity* price
- # set dictionary key to item_name and value to quantity
- self.items[ item_name ] = quantity
- def remove_item( self , item_name , quantity , price ) :
- if quantity > self.items[ item_name ] :
- self.total -= self.items[ item_name ] * price
- del self.items[item_name]
- else :
- self.total -= quantity * price
- self.items[ item_name ] -= quantity
- def checkout( self , cash_paid ) :
- if cash_paid >= self.total :
- return cash_paid - self.total
- else :
- return "Cash paid not enough"
- class Shop( ShoppingCart ) :
- def __init__( self ) :
- self.quantity = 100
- def remove_item(self ,quantity = 1 ) :
- self.quantity -= quantity
- if __name__ == '__main__' :
- sc = ShoppingCart()
- # to check class attributes and to ensure methods are working correctly , we are printing them
- # printing attributes are optional
- # first argument is quantity ,second argument is price
- # add 50 items whose price is 30
- sc.add_item( 'NoteBook' , 50 , 30 )
- print( sc.items )
- print( sc.items['NoteBook'] )
- print( sc.total )
- #cash_paid is 2000 and is more than 1500 (50*30)
- print ( 'Balance : ')
- print( sc.checkout( 2000 ))
- # remove 10 items whose price is 30
- sc.remove_item('NoteBook' , 10 , 30)
- print( sc.items )
- print( sc.items['NoteBook'] )
- print( sc.total )
- #cash_paid is 1000 and Less than 1200 (40*30)
- print( sc.checkout(1000 ))
- # remove 41 items whose price is 30
- #item being removed is more than existing items ,so item NoteBook will be removed from dictionary
- sc.remove_item('NoteBook' , 41 , 30)
- print( sc.items )
- print( sc.total )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement