Reading the Order
So far, you've written the calls of add_item() yourself. In a real shop, nobody writes them: the website sends what the customer added, as lines of text. Each line has the name, the price and the quantity, separated by semicolons: "Coffee;7;2". The editor has these lines in a new list, order, under the cart, and the calls at the bottom are gone. Your program will make them itself, one for each line.
You know everything it takes. .split(";") cuts a line into a list of texts, unpacking puts them into variables, and int() turns a text with a number into a number:
line = "Matilda;240"
title, pages = line.split(";")
print(title)
print(int(pages) + 10)Matilda
250Without int(), the pages would still be text, and pages + 10 would end with TypeError: can only concatenate str (not "int") to str.
And the bad lines? The eggs have a quantity of 0, so add_item() raises its ValueError, as before. But a website can send worse. If a customer types three instead of 3, int("three") raises a ValueError too, Python's own: ValueError: invalid literal for int() with base 10: 'three'.
One try with except ValueError catches both, as long as the calls of int() are inside the try. The except prints the message, and the loop goes on with the next line: one bad line doesn't stop the whole order.
As with the cart, the exercise also runs your program with other lines in order, so leave them as they are.
Instructions
- 1
Above
print_receipt(cart), write aforloop that goes throughorder. Split each line with.split(";")and unpack it intoname,priceandquantity. Then, in atryblock, calladd_item(cart, name, int(price), int(quantity)), and underexcept ValueError as error:, print the message as before, but withnameinstead ofEggs. The output is the same as at the end of the previous exercise:Can't add Eggs: the quantity must be at least 1and a receipt with the coffee and six cartons of milk. - 2
Add one more line to the end of
order, with a quantity that the customer typed in words:"Tea;3;three",. A second message appears above the receipt,Can't add Tea: invalid literal for int() with base 10: 'three', and the receipt stays the same. If the program ends with the error instead, check that both calls ofint()are inside thetry.