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 Item object from the values it gets 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.
A good program also checks its data. Adding something with a quantity of 0, or even -1, makes no sense. add_item() can find that out, but it isn't the one to decide what happens next. Print a message? Skip the item? Ask the customer again? That's up to the code that called it. So, as in the lesson on exceptions, add_item() raises a ValueError, and the caller catches it with try and except:
def add_guest(guests, name):
if name == "":
raise ValueError("a guest needs a name")
guests.append(name)
party = ["Anna"]
try:
add_guest(party, "")
except ValueError as error:
print("Can't add the guest:", error)
add_guest(party, "Tom")
print(party)Can't add the guest: a guest needs a name
['Anna', 'Tom']Like return, raise ends the function at once, so the empty name isn't appended. The text you give ValueError is what print(error) shows under except. Without try, the error would end the whole program. For the eggs in this exercise, it would look something like this:
Traceback (most recent call last):
File "<exec>", line 59, in <module>
File "<exec>", line 54, in add_item
ValueError: the quantity must be at least 1Read it from the bottom: the error with your message, then the line in add_item() where it was raised, and above it the line at the bottom of the program that called the function.
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
- 1
Under
print_receipt()(above the code at the bottom), write a functionadd_item(items, name, price, quantity)that appends a newItemwith these values toitems. Then, at the bottom, aboveprint_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: $0andTo pay: $50. If the delivery still costs $5, check the condition indelivery_price(). - 2
At the start of
add_item(), add a check: ifquantityis less than1, raiseValueError("the quantity must be at least 1"). The receipt doesn't change, because the coffee's quantity is fine. - 3
Under the coffee, add eggs with a quantity of 0:
add_item(cart, "Eggs", 4, 0). Put the call in atryblock, and underexcept ValueError as error:, printCan't add Eggs:and the message. The program printsCan't add Eggs: the quantity must be at least 1above the receipt, and the eggs don't get onto it.