10. Its not all animals and fruits


Everything is working fine with my code I just have a question about the code thats given.
In the 'add_item' function why is
self.items_in_cart[product] = price
Shouldn't this be set to product?

Thanks for your help.

class ShoppingCart(object):
    """Creates shopping cart objects
    for users of our fine website."""
    items_in_cart = {}
    def __init__(self, customer_name):
        self.customer_name = customer_name

    def add_item(self, product, price):
        """Add product to the cart."""
        if not product in self.items_in_cart:
            self.items_in_cart[product] = price
            print product + " added."
            print product + " is already in the cart."

    def remove_item(self, product):
        """Remove product from the cart."""
        if product in self.items_in_cart:
            del self.items_in_cart[product]
            print product + " removed."
            print product + " is not in the cart."

my_cart = ShoppingCart("op")


Things to note..

items_in_cart is an empty dictionary.

add_item method takes two arguments.

product and price.

if not product in self.items_in_cart
This line checks using key of dictionary ( if product) is in cart or not.

(what do you think this line return...
"X" in {"X": 1, "Y": 2} ?? True! )

when you do this..

"shoe" is product (key)
500 is price. (value)

But if shoe is already there,It will not added.
As our dictionary is already empty so It will add it.


items_in_cart is a dictionary, using self.items_in_cart[product] = price will add a key value pair to dictionary with key product and value price, doing self.items_in_cart[product] = product will add a key value pair with product key and value product

here is the general syntax for inserting into dictionary:

dictionaryName[keyName] = Value

hope this helps


oh okay, i forgot that it is a dictionary.. Thanks a lot!!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.