Skip to content

Instantly share code, notes, and snippets.

@jerryOkafor
Created April 13, 2017 07:40
Show Gist options
  • Save jerryOkafor/0f36030a54a3b5362ae0fcd46ce857d1 to your computer and use it in GitHub Desktop.
Save jerryOkafor/0f36030a54a3b5362ae0fcd46ce857d1 to your computer and use it in GitHub Desktop.
ShoppingCart.py with two methods to add and remove items and inheritance to for one of the Andela Home Study Exercise.
class ShoppingCart:
def __init__(self):
self.total = 0
self.items = {}
def add_item(self, item_name, quantity, price):
self.total += price * quantity
self.items.update({item_name: quantity})
def remove_item(self, item_name, quantity, price):
self.total -= price * quantity
if quantity > self.items[item_name]:
self.items.pop(item_name)
else:
self.items[item_name] -= quantity
def output(self):
print("Total: ", self.total)
print(self.items)
def checkout(self, cash_paid):
if self.total > cash_paid:
return "Cash paid not enough"
return cash_paid - self.total
class Shop(ShoppingCart):
def __init__(self):
super().__init__()
self.quantity = 100
def remove_item(self, item_name="", quantity=0, price=0):
if item_name == "" or quantity == 0 or price == 0:
self.quantity -= 1
else:
super().remove_item(item_name, quantity, price)
def print_qty(self):
print("Quantity: ", self.quantity)
# myCart = ShoppingCart()
#
# myCart.add_item("Test", 4, 100)
# myCart.add_item("Test1", 4, 150)
# myCart.add_item("Test2", 4, 180)
#
# myCart.remove_item("Test", 1, 50)
# myCart.remove_item("Test2", 3, 50)
#
# print("Balance: ", myCart.checkout(5000))
myCart = Shop()
myCart.add_item("Test", 4, 100)
myCart.add_item("Test1", 4, 150)
myCart.add_item("Test2", 4, 180)
myCart.remove_item("Test", 1, 50)
myCart.remove_item("Test2", 3, 50)
myCart.print_qty()
myCart.remove_item()
myCart.print_qty()
myCart.remove_item()
myCart.print_qty()
myCart.remove_item()
myCart.print_qty()
myCart.remove_item()
myCart.print_qty()
print("Balance: ", myCart.checkout(5000))
myCart.output()
@okoro056
Copy link

You are the man.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment