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"]
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
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']
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.