49. Print a receipt
Write a program that prints a shop receipt. It reads:
- a first line with the number of items, n (it can be 0);
- then n lines, each an item's name and price separated by a comma, such as
Coffee,2.5.
It prints one line per item, then a line of dashes, then the total:
- An item's line is its name, left-aligned and padded with spaces to 16 characters, then its price right-aligned in 8 characters with exactly 2 decimals. So the line is 24 characters, and the prices' decimal points line up.
- The dashes are 24
-characters. - The last line is the word
Totallaid out like an item's name, then the sum of all the prices, laid out like a price.
With f-strings: f"{name:<16}{price:>8.2f}".
Example 1
Input
3
Coffee,2.5
Bagel with jam,3.75
Tea,1.2Output
Coffee 2.50
Bagel with jam 3.75
Tea 1.20
------------------------
Total 7.45ExplanationNames padded to 16, prices to 8.
Example 2
Input
0Output
------------------------
Total 0.00ExplanationNo items: just the dashes and a 0 total.
Constraints
- n is a whole number from 0 to 20.
- A name has 1 to 16 characters and no comma; there are no spaces around the comma.
- A price is from 0 to 999.99 with at most 2 decimals.
- Print nothing else. A prompt inside
input()is fine: the tests leave it out of the output.
Submit also runs 4 more tests you can't see.
Practises String Formatting Deep Dive (lesson 24).
name, price = line.split(",")splits a line at its comma into two strings. Turn the price into a number withfloat()and add it to a running total.- In an f-string,
{name:<16}pads the name with spaces to 16 characters, aligned left, and{price:>8.2f}writes the price with 2 decimals, aligned right in 8 characters. "-" * 24is the line of dashes. The wordTotalgets the same:<16as a name, and the total the same:>8.2fas a price, even when there were no items.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
Code
# Read how many items there are, then each "name,price" # line, and print the receipt: each item, a line of 24 # dashes, and the total.
Run your code to see how it does on the test cases, or Submit to check every test.