Preparation

Verify how Python reacts if you consecutively execute the following instructions in an interactive Python session.

  1. >>> d = {'buns': 6, 'cookies': 11, 'bananas': 12}
    >>> d['bananas']

  2. >>> d['yoghurts'] = 12
    >>> len(d)

  3. >>> 'bananas' in d

  4. >>> d['toothbrushes']

  5. >>> d.get('toothbrushes', 0)

  6. >>> products = list(d.keys())
    >>> products.sort()
    >>> print(products)

  7. >>> del d['buns']
    >>> 'buns' in d

Make sure you understand why the different results are generated.

Assignment

Apply what you have just learned to complete the bodies of the functions below. Your implementation must endure the doctest given.

def addProduct(shoppingcart, product, amount=0):

    """
    Adds a certain amount of a product to a shopping cart. 
    >>> shoppingcart = {}
    >>> addProduct(shoppingcart, 'cookies', 10)
    10
    >>> 'cookies' in shoppingcart
    True
    >>> shoppingcart['koekjes']
    10
    >>> amountCookies = addProduct(shoppingcart, 'cookies', 5)
    >>> amountCookies
    15
    >>> shoppingcart['cookies']
    15
    >>> addProduct(shoppingcart, 'yoghurts', -4)
    0
    >>> 'yoghurts' in shoppingcart
    False
    """
def removeProduct(shoppingcart, product, amount=1):

    """
    Deletes a certain amount of a product from a shopping cart.

    >>> shoppingcart = {}
    >>> addProduct(shoppingcart, 'cookies', 10)
    10
    >>> removeProduct(shoppingcart, 'cookies', 4)
    6
    >>> shoppingcart['cookies']
    6
    >>> removeProduct(shoppingcart, 'cookies', 8)
    0
    >>> 'cookies' in shoppingcart
    False
    """