Skip to the content

Project: clean up this program

Python · Unit 19: Clean code

This program charges a cart. It works, but it's hard to read: the function is called f, its variables are loose letters and it does two things at once.

You are going to split it into pieces with names, docstrings and hints. The total has to keep coming out exactly the same.

def f(l):
    x = 0
    for i in l:
        x = x + i["price"] * i["qty"]
    if x > 500:
        return x * 0.9
    return x

c = [{"price": 300, "qty": 2}]
print(f(c))

Prints

540.0

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Put the lines in order

    Put the program in order. line_total charges one item, and at the end its description is printed too.

  2. 2. Write the code

    Write subtotal(cart): it adds up the line total of every item, and gives back 0 when the cart comes in empty. line_total is already written; use it instead of repeating the math.

  3. 3. Write the code

    Write total(cart): the subtotal, with 10% off when the subtotal goes past 500. Exactly 500 gets no discount. subtotal is already written.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →