Create a ShoppingCart in Python OOP

shopping cart mini project in python
python project on shopping cart
how to create a shopping cart python
python dictionary shopping cart
python shopping cart github
shopping cart gui python
12.11 lab program: online shopping cart (continued python 3)
create a class called shoppingcart in python

I have a lab test in python oop.

Create a class called ShoppingCart.

Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items.

Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item.

Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly.

If the quantity of an item to be removed exceeds the current quantity of that item in the cart, assume that all entries of that item are to be removed.

Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough".

Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100. Make sure Shop inherits from ShoppingCart.

In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one.

And here is my code

class ShoppingCart(object):

    def __init__(self):
        self.total = 0
        self.items = dict()

    def add_item(self, item_name, quantity, price):
        if item_name != None and quantity >= 1:
            self.items.update({item_name: quantity})
        if quantity and price >= 1:
            self.total += (quantity * price)

    def remove_item(self, item_name, quantity, price):
        self.total -= (quantity * price)
        try:
            if quantity >= self.items[item_name]:
                self.items.pop(item_name, None)
            self.items[item_name] -= quantity
        except(KeyError, RuntimeError):
            pass

    def checkout(self, cash_paid):
        balance = 0
        if cash_paid < self.total:
            return "Cash paid not enough"
        balance = cash_paid - self.total
        return balance


class Shop(ShoppingCart):

    def __init__(self):
        self.quantity = 100

    def remove_item(self):
        self.quantity -= 1

And the unittest

import unittest

class ShoppingCartTestCases(unittest.TestCase):
  def setUp(self):
    self.cart = ShoppingCart()
    self.shop = Shop()

  def test_cart_property_initialization(self):
    self.assertEqual(self.cart.total, 0, msg='Initial value of total not correct')
    self.assertIsInstance(self.cart.items, dict, msg='Items is not a dictionary')

  def test_add_item(self):
    self.cart.add_item('Mango', 3, 10)

    self.assertEqual(self.cart.total, 30, msg='Cart total not correct after adding items')
    self.assertEqual(self.cart.items['Mango'], 3, msg='Quantity of items not correct after adding item')

  def test_remove_item(self):
    self.cart.add_item('Mango', 3, 10)
    self.cart.remove_item('Mango', 2, 10)

    self.assertEqual(self.cart.total, 10, msg='Cart total not correct after removing item')
    self.assertEqual(self.cart.items['Mango'], 1, msg='Quantity of items not correct after removing item')

  def test_checkout_returns_correct_balance(self):
    self.cart.add_item('Mango', 3, 10)
    self.cart.add_item('Orange', 16, 10)

    self.assertEqual(self.cart.checkout(265), 75, msg='Balance of checkout not correct')
    self.assertEqual(self.cart.checkout(25), 'Cash paid not enough', msg='Balance of checkout not correct')

  def test_shop_is_instance_of_shopping_cart(self):
    self.assertTrue(isinstance(self.shop, ShoppingCart), msg='Shop is not a subclass of ShoppingCart')

  def test_shop_remove_item_method(self):
    for i in range(15):
      self.shop.remove_item()

    self.assertEqual(self.shop.quantity, 85)

The code passes all the testcases. But when i try to submit, it fails and says it doesn't meet all the test spec. I have double checked it and catched any error that may arise but its still the same. I don't know what I'm missing. Is there a way around this?

in the remove_item method you have to check if item_name in self.items: before doing anything example:

if item_name in self.items: if quantity < self.items[item_name] and quantity > 0: self.items[item_name] -= quantity self.total -= price*quantity

Python OOP shopping cart, You need to think about what a cart does, and create those functions. Why make cartlist a dictionary? You should make it a list instead. You can  An e-commerce site can be created in many ways, whether that means using a third-party application like osCommerce or writing one from scratch in classic, procedural PHP code. In this article, web developer Larry Ullman presents the class structure you could use to create the core of a shopping cart application using object-oriented programming.

class ShoppingCart(object):

    def __init__(self):
      self.total = 0
      self.items = {}

    def add_item(self, item_name, quantity, price):
        self.total += (quantity * price)
        self.items = {item_name : quantity}


    def remove_item(self, item_name, quantity, price):
        self.total -= (quantity * price)
        if quantity > self.items[item_name]:
          del self.items[item_name]
        self.items[item_name] -= quantity


    def checkout(self, cash_paid):
        balance = 0
        if cash_paid < self.total:
          return "Cash paid not enough"
        balance = cash_paid - self.total
        return balance


class Shop(ShoppingCart):

    def __init__(self):
      ShoppingCart.__init__(self)
      self.quantity = 100

    def remove_item(self):
        self.quantity -= 1

Python Object Oriented Shopping Cart, We will need to build a ShoppingCart class that creates a shopping cart with a total ( _total ) which starts at 0 , an empty list of items ( _items ), and an optional  OOP in Python. Python is a great programming language that supports OOP. You will use it to define a class with attributes and methods, which you will then call. Python offers a number of benefits compared to other programming languages like Java, C++ or R. It's a dynamic language, with high-level data types.

class ShoppingCart {
    constructor() {
        this.total = 0;
        this.items = {};
    }
    add_item(item_name, quantity, price) {
        // this.items = { item_name:quantity };
        this.items[item_name] = quantity;
        this.total += (quantity * price);

    }
    remove_item(item_name, quantity, price) {
        // confusion set it
        var prevQuantity = this.items[item_name];
        if (prevQuantity) {
            if (prevQuantity >= quantity) {
                var currentQuantity = prevQuantity - quantity;
                this.items[item_name] = currentQuantity;
                this.total -= (quantity * price);
            } else {
                delete this.items[item_name];
                this.total -= (prevQuantity * price);
            }
        }
    }
    checkout(cash_paid) {
        var balance = 0;
        if (cash_paid < this.total) {
            return "Cash paid not enough.";
        } else {
            balance = cash_paid - this.total;
            return balance;
        }
    }
}
class Shop extends ShoppingCart {
    constructor() {
        super();
        this.quantity = 100;
    }
        remove_item() {
            this.quantity--;
        }
    }


let cart = new ShoppingCart();
cart.add_item("Mango", 3, 10);
cart.add_item("Orange", 16, 10);
cart.checkout(265)

shoppingCart.cart, Source code for shoppingCart.cart. #!/usr/bin/python # -*- encoding: utf-8 -*- ####​###  Create a class called ShoppingCart. Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items . Create a method add_item that requires item_name , quantity and price arguments.

HELP ME OBJECT ORIENTED PROGRAMMING Create a , OBJECT ORIENTED PROGRAMMING Create a class called ShoppingCart. could some one tell me whats wrong with my code especially the  One of the popular approach to solve a programming problem is by creating objects. This is known as Object-Oriented Programming (OOP). An object has two characteristics: attributes; behavior; Let's take an example: Parrot is an object, name, age, color are attributes; singing, dancing are behavior; The concept of OOP in Python focuses on creating reusable code.

Python OOP challenge, Create a class called ShoppingCart. Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty  Python Objects (Instances) While the class is the blueprint, an instance is a copy of the class with actual values, literally an object belonging to a specific class. It’s not an idea anymore; it’s an actual animal, like a dog named Roger who’s eight years old. Put another way, a class is like a form or questionnaire.

Creating a Shopping Cart Class Using Object-Oriented , Larry Ullman presents the class structure you could use to create the core of a shopping cart application using object-oriented programming. The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class. You declare other class methods like normal functions with the exception that the first argument to each method is self.

Comments
  • "submit" where? Is there any way we can try this ourselves? What error message does the platform (or wherever you try to submit your code) give you?
  • If you're sure that the unit tests there are the same as the ones that are being run when you submit your work, then you'd be best checking with the person who runs your lab. If you're not sure, then that would also be a good thing to check with them.
  • While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run.