livepython.net

248. Python Program to Track Expenses by Category

MediumPhase 2 · Practice

This one takes a few steps, and you have used every tool in it: a while loop, split() and a dictionary.

Overview

An expense tracker shows where your money goes. Budget apps group your spending into categories, like food or travel, and add up each one.

Problem Statement

Ingrid writes down every expense as a category and an amount in coins, like food 12.50. Read the expenses, one per line, until a line says end. Then print:

  1. The total for each category, as <category>: <total>, in the order the categories first appeared.
  2. Total: <total>: all the expenses added up.

Print every amount with 2 decimal places. If there are no expenses at all, print only No expenses. Categories must match exactly: food and Food are two different categories.

Examples

Example 1. Input:

food 12.50
bus 2.75
food 8.25
books 30
bus 2.75
end

gives:

food: 20.75
bus: 5.50
books: 30.00
Total: 56.25

Why: food is 12.50 + 8.25 = 20.75, and bus is 2.75 + 2.75 = 5.50. All five amounts add up to 56.25.

Example 2. Input:

rent 500
food 120
fun 45.50
food 380
end

gives:

rent: 500.00
food: 500.00
fun: 45.50
Total: 1045.50

Why: food is 120 + 380 = 500. Food's second amount comes last, but food keeps its place: the order is rent, food, fun, as they first appeared.

Input

One expense per line: a one-word category, a space, then the amount (a number above 0, maybe with a decimal point). The last line is always end. Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.

Output

One line for each category, then the Total: line. Or only No expenses. The tests try 7 different inputs, also no expenses, one category only and Food with a capital F.

Try it first. The solution opens when you solve this question, or after 3 tries with Submit.

Finish this chapter firstChapter 13 · Dictionaries
solution.py
# write your code here

EXPECTED OUTPUT

1food: 20.75
2bus: 5.50
3books: 30.00
4Total: 56.25

YOUR OUTPUT

Press Run to see your output here. Lines are compared with the expected output.