Adding Items

Customers keep adding things to their carts, so your program needs a function for it: add_item(items, name, price, quantity). It creates a new dictionary for the item and adds it to the end of the list with .append().

When you pass a list to a function, the function gets the very same list, not a copy. So when add_item() appends to items, the item gets into cart, and the receipt printed afterwards shows it. That's why the function doesn't need to return anything. This doesn't contradict what you learned about local variables: assigning to a variable inside a function creates a new local variable, but .append() doesn't assign anything, it changes the list itself.

A good program also checks its data. Adding something with a quantity of 0, or even -1, makes no sense. So at the start of the function, check the quantity, and if it's less than 1, print a message and end the function with return. Since return ends the function, the code that adds the item doesn't run. A return without a value is fine: the function doesn't give anything back, it just stops. Here's the same idea with a list of guests ("" is an empty text, with nothing between the quotes):

def add_guest(guests, name):
    if name == "":
        print("A guest needs a name.")
        return
    guests.append(name)


party = ["Anna"]
add_guest(party, "")
add_guest(party, "Tom")
print(party)
A guest needs a name.
['Anna', 'Tom']

The calls go at the bottom, above print_receipt(cart): first the cart changes, then the receipt is printed. And the coffee brings a surprise: with it, the order costs exactly $50.

Instructions

Under print_receipt() (above the code at the bottom), write a function add_item(items, name, price, quantity) that adds a dictionary with the keys "name", "price" and "quantity" to the end of items.

At the bottom, above print_receipt(cart), add two bags of coffee at $7 each: add_item(cart, "Coffee", 7, 2). A new line appears on the receipt, Coffee: 2 x $7 = $14, and the total is now exactly $50, so the delivery is free: Delivery: $0 and To pay: $50. If the delivery still costs $5, check the condition in delivery_price().

At the start of add_item(), add a check: if quantity is less than 1, print Can't add Eggs: the quantity must be at least 1. with the item's name instead of Eggs, and end the function with return. Try it under the coffee: add_item(cart, "Eggs", 4, 0). The message appears above the receipt, and the eggs don't get onto it.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

5/7