BBampaa

Lessons › Python

Python lesson

Automate a report

Load next week's file, run it again, and the report writes itself. Loops, filters, len and f-strings, all from earlier levels.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

A loop runs the same summary for every store and prints a line for each:

for store in ["Lagos", "Abuja"]:
    rows = df[df["Store"] == store]
    print(f"{store}: {rows['Revenue'].sum()} from {len(rows)} orders")

Output:

Lagos: 264 from 5 orders
Abuja: 195 from 3 orders

Key points

f"{store}: {total}"An f-string: text with values dropped in.
for store in stores:Repeat the summary for every store, however many there are.
def report(df):Wrap it in a function, and the whole report is one call.

Everything from the earlier levels, working together.

Practice

Try each one in your head first, then open the answer.

1. Build a line that prints the product and its total, like Earbuds: 350.
print(f"{product}: {total}")
2. Build the first line of a loop over the stores list.
for store in stores:
3. Print each product's total revenue on its own line, like Earbuds: 350.
for product in df["Product"].unique():
    total = df[df["Product"] == product]["Revenue"].sum()
    print(f"{product}: {total}")
4. Write a function store_total(name) that returns the total revenue for that store. Print store_total("Lagos").
def store_total(name):
    return df[df["Store"] == name]["Revenue"].sum()
print(store_total("Lagos"))
5. Print one line per store, like: Lagos: 264 from 5 orders
for store in ["Lagos", "Abuja"]:
    rows = df[df["Store"] == store]
    print(f"{store}: {rows['Revenue'].sum()} from {len(rows)} orders")

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed