Module 2 · Python for Data Analytics
Lists, dictionaries, loops and functions
The core Python you need before pandas: store many values in lists and dictionaries, repeat work with loops, decide with if, and package logic in functions.
About 30 minutes
The problem
Bisi has a week of daily sales from one Kolanut depot, and a rule from finance: lines worth ₦500,000 or more need a second signature. She could check each number by eye, but next week there will be another list, and the week after that.
Before you can use pandas well, you need the four ideas it's built on: lists (many values in order), dictionaries (values looked up by name), loops (do something for each value) and functions (a named, reusable calculation). pandas does most of the looping for you, but when something goes wrong, these are the ideas you'll need to understand what happened.
The concept
Lists: values in order
daily_sales = [412500, 389000, 455250, 501300, 298700, 610400, 352900]len(daily_sales)is how many values there are (7).sum(daily_sales),min(...),max(...)work on any list of numbers.- Positions start at 0:
daily_sales[0]is the first value,daily_sales[-1]the last. daily_sales[1:3]is a slice: positions 1 and 2 (the end position isn't included).daily_sales.append(480000)adds a value to the end.
Dictionaries: values by name
A dictionary maps keys to values. It's how you'd store one row of data, or a lookup table:
category_of = {1: "Beverages", 5: "Snacks", 9: "Household", 13: "Personal care"}
category_of[9]That returns 'Household'. Add or change an entry with category_of[2] = "Beverages". Ask for a key that isn't there and you get a KeyError; category_of.get(99, "Unknown") returns a default instead.
Loops: do it for each one
for amount in daily_sales:
print(amount)The indented lines run once for each value. Indentation (4 spaces, which Colab adds for you) is how Python knows which lines belong to the loop.
Decisions: if, elif, else
amount = 610400
if amount >= 500000:
print("Needs a second signature")
elif amount >= 400000:
print("Check the customer's credit limit")
else:
print("OK")Comparisons give True or False: == (equal), != (not equal), <, <=, >, >=. Combine them with and, or and not.
Functions: name a calculation once, use it everywhere
def line_revenue(quantity, unit_price, discount_pct=0):
"""Revenue of one order line after its discount."""
return quantity * unit_price * (1 - discount_pct / 100)def starts a function, the names in brackets are its parameters, and return sends the answer back. discount_pct=0 is a default: leave it out and it's 0. Now line_revenue(14, 18600, 5) gives 247380.0 and line_revenue(10, 9900) gives 99000.0.
Example
A week of depot sales, checked against finance's rule, with a summary at the end:
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
daily_sales = [412500, 389000, 455250, 501300, 298700, 610400, 352900]
flagged = []
for day, amount in zip(days, daily_sales):
if amount >= 500000:
flagged.append(day)
total = sum(daily_sales)
average = total / len(daily_sales)
best_day = days[daily_sales.index(max(daily_sales))]
print(f"Week total: ₦{total:,}")
print(f"Daily average: ₦{average:,.0f}")
print(f"Best day: {best_day}")
print(f"Need a second signature: {flagged}")Week total: ₦3,020,050
Daily average: ₦431,436
Best day: Sat
Need a second signature: ['Thu', 'Sat']Walkthrough
zip(days, daily_sales)pairs the two lists up:("Mon", 412500),("Tue", 389000)… so each pass of the loop gets a day and its amount.flagged = []starts an empty list;appendadds each day that meets the rule.daily_sales.index(max(daily_sales))finds the position of the largest value (5), anddays[5]turns that position into a day name.- Now build a dictionary of totals by category from a few order lines, the way pandas'
groupbywill later:
lines = [("Beverages", 247380), ("Snacks", 99000), ("Beverages", 92400), ("Household", 279600), ("Snacks", 56760)]
totals = {}
for category, revenue in lines:
totals[category] = totals.get(category, 0) + revenue
totals- Read the result:
{'Beverages': 339780, 'Snacks': 155760, 'Household': 279600}.totals.get(category, 0)returns the running total so far, or 0 the first time a category appears. - Add
line_revenuefrom the Concept to your notebook and call it with and without a discount. - Deliberately break the indentation of one line inside a loop and run it. Read the
IndentationError, then fix it. Learning to read error messages is half of programming.
Practice
Use the week of sales in the Example, in your notebook.
Practice
What is the total of the days whose sales were below ₦400,000? Write a loop with an if inside it.
Practice
Write a function discount_cost(quantity, unit_price, discount_pct) that returns the money a discount took off a line. What does discount_cost(20, 15600, 10) return?
Practice
In the category totals from the Walkthrough, which category has the highest total? Use max(totals, key=totals.get).
Challenge
Challenge · optional
Using a loop and a counter, on how many days were sales above the week's average?
Check your understanding
Answer every question to check.