10 - Not all fruits and animals


#1

Here is my given code:

class ShoppingCart(object):
"""Creates shopping cart objects
for users of our fine website."""
items_in_cart = {}
def init(self, customer_name, my_cart):
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("Bill")
my_cart.add_item("Beans", 30)

The given task is to simply add the variable "my_cart" and add an/some item(s). That is what I've done at the bottom. But the error message still only informs me that "ShoppingCart" isn't defined and asks if I have made a variable called "my_cart"

Any help?


#2

Perhaps your indentation isn't right, can't tell though, since you haven't marked the code as pre-formatted text!


#3

You have in __init__ function argument my_cart which is different than in example given in this exercise and this can cause error.


#4
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("Elvis")
    my_cart.add_item("banjo", 10)

I'm getting the same error,
"File "python", line 24, in ShoppingCart
NameError: name 'ShoppingCart' is not defined


#5

Nm, found it, indentation is wrong on:

my_cart = ShoppingCart("Elvis")
my_cart.add_item("banjo", 10)