Module 2 of 6 · 30 minutes

Data structures, logic and functions

Real data comes in collections. This module gives you the tools to store, loop over and make decisions about it.

Learning objectives

  • Create, index and slice lists
  • Use dictionaries — the same shape as JSON
  • Write if/elif/else conditions
  • Loop with for, enumerate and list comprehensions
  • Define and call functions

2.1 Lists

reviews = ["Love it", "Arrived damaged", "Great value", "Too small"]
print(reviews[0])        # first item: "Love it"
print(reviews[-1])       # last item: "Too small"
print(len(reviews))      # 4
reviews.append("Would buy again")
print(reviews[1:3])      # slice: ["Arrived damaged", "Great value"]
"Love it"0-4"Arrived damaged"1-3"Great value"2-2"Too small"3-1indexfrom endreviews[0] → "Love it" reviews[-1] → "Too small" reviews[1:3] → middle two
List positions count from 0 at the front and from −1 at the back. Slices take a range.

2.2 Dictionaries

A dictionary maps keys to values — the same shape as JSON, which is how AI APIs send and receive data.

order = {"id": "GFY-10422", "item": "Bamboo board", "qty": 2, "price": 24.99}
print(order["item"])                 # "Bamboo board"
order["status"] = "dispatched"       # add a key
total = order["qty"] * order["price"]
print(order.get("discount", 0))      # safe lookup with a default: 0
keysvalues"id""GFY-10422""item""Bamboo board""qty"2"price"24.99order["item"] → "Bamboo board"
A dictionary maps keys to values — exactly the shape of the JSON that AI APIs send and receive.

2.3 Conditions

rating = 2
if rating >= 4:
    sentiment = "positive"
elif rating == 3:
    sentiment = "neutral"
else:
    sentiment = "negative"
print(sentiment)

Indentation (four spaces) matters in Python: it shows which lines belong to the if.

2.4 Loops

for review in reviews:
    print(review.upper())

# loop with a counter
for i, review in enumerate(reviews, start=1):
    print(i, review)

# list comprehension: build a new list in one line
lengths = [len(r) for r in reviews]
short = [r for r in reviews if len(r) < 12]

2.5 Functions

Functions package code you'll reuse. You'll write one later to call an AI model.

def classify_rating(rating):
    # Return a sentiment label for a 1-5 star rating.
    if rating >= 4:
        return "positive"
    if rating == 3:
        return "neutral"
    return "negative"

ratings = [5, 2, 3, 4, 1]
labels = [classify_rating(r) for r in ratings]
print(labels)    # ['positive', 'negative', 'neutral', 'positive', 'negative']
rating = 2classify_rating(rating)if ≥ 4 → positive3 → neutral, else negative"negative"inputreturn
A function takes inputs, runs its logic, and returns a result you can reuse anywhere.
Exercise: count the complaints

Given a list of review dictionaries like {"text": "Arrived damaged", "stars": 1}, write a function that returns how many reviews have 2 stars or fewer, and a list of their texts.

Show a solution
reviews = [
    {"text": "Love it", "stars": 5},
    {"text": "Arrived damaged", "stars": 1},
    {"text": "Too small", "stars": 2},
]

def complaints(reviews):
    bad = [r["text"] for r in reviews if r["stars"] <= 2]
    return len(bad), bad

print(complaints(reviews))   # (2, ['Arrived damaged', 'Too small'])

Key takeaways

  • Lists hold ordered items; index from 0, and -1 is the last.
  • Dictionaries map keys to values, like JSON.
  • Indentation defines code blocks.
  • List comprehensions build lists concisely.
  • Functions package reusable logic.