10. Its not all animals and fruits


#1

Hi!
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."
        else:
            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."
        else:
            print product + " is not in the cart."


my_cart = ShoppingCart("op")
my_cart.add_item("shoe",500)

#2

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..
my_cart.add_item("shoe",500)

"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.


#3

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


#4

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


#5

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