Python Project: A Receipt Builder
A receipt lists what was bought, each price, and the total. The text tools from this entry build every line of it.
Cut the spaces from every part
map() runs str.strip on each part. The three clean parts come back as a list.
line = " pencil, 2, 1.50 "
parts = list(map(str.strip, line.split(",")))
print(parts)Turn the parts into numbers
int() turns the count text into a number. float() turns the price text into a number.
parts = ["pencil", "2", "1.50"]
qty = int(parts[1])
price = float(parts[2])
print(qty * price)One receipt line, lined up
The name takes twelve spaces on the left. The cost takes eight spaces on the right.
name = "Pencil"
cost = 3.0
print(f"{name:<12}{cost:>8.2f}")Example
lines = ["pencil, 2, 1.50", "notebook, 1, 4.25", "ruler, 3, 0.80"]
print("SHOP RECEIPT")
print("-" * 24)
total = 0.0
for line in lines:
parts = list(map(str.strip, line.split(",")))
name = parts[0].title()
qty = int(parts[1])
price = float(parts[2])
cost = qty * price
total = total + cost
print(f"{name:<12}{qty:>4}{cost:>8.2f}")
print("-" * 24)
print(f"{'Total':<16}{total:>8.2f}")
print("Thank you")Key points
- Receipt: a list of bought items with prices and a total
- Use strip() and title() to clean each item name first
- Use split(",") to break a bought line into its parts
- Use map(str.strip, parts) to cut the spaces from every part at once
- Use int() and float() to turn the count and price text into numbers
- Use f-strings with widths to line the prices up in a column
- Add each line cost to a running total as the lines print
In this example, the list holds three bought lines in plain text. The loop splits each line at its commas and strips every part. title() cleans the name, and int() and float() turn the count and price into numbers. Each line prints its name, count, and cost in columns. The total of 9.65 proves the three costs add up.
Note
This project uses only the text tools from this entry: cleaning, splitting, and formatting.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does line.split(",") do to "pencil,2,1.50"?