Skip to main content

Phase 5 🧩 — Functions & Modules

Topics: def functions, return values, lambda, list comprehension, importing modules

Learn to write reusable, organised code. Functions and modules are how you stop writing scripts and start building systems.


🔄 Exercise Flow


📚 Prerequisites

Before starting these exercises, make sure you've read:


🔰 Starter: Utility Functions Pack

Time: 12 minutes

Write a collection of small utility functions that perform common data transformations.

Learning Objectives

  • Define functions with def and return
  • Use positional and keyword arguments
  • Document functions with docstrings
  • Combine functions to build a small toolkit

Starter Code

# Starter: Utility Functions Pack

# TODO: Implement these functions:

def celsius_to_fahrenheit(c):
"""Convert Celsius to Fahrenheit."""
# Your code here
pass

def is_even(n):
"""Return True if n is even, False otherwise."""
# Your code here
pass

def count_vowels(text):
"""Return the number of vowels (a, e, i, o, u) in text."""
# Your code here
pass

def reverse_words(sentence):
"""Reverse the order of words in a sentence."""
# Your code here
pass

# --- Test your functions ---
print(celsius_to_fahrenheit(0)) # Expected: 32.0
print(celsius_to_fahrenheit(100)) # Expected: 212.0
print(is_even(7)) # Expected: False
print(count_vowels("hello world")) # Expected: 3
print(reverse_words("Python is fun")) # Expected: "fun is Python"

Expected Output

32.0
212.0
False
3
fun is Python

⭐ Medium: Data Processing Pipeline

Time: 22 minutes

Build a data processing pipeline that uses lambda, list comprehensions, and functional programming patterns (map, filter) to transform raw data.

Learning Objectives

  • Write and use lambda functions
  • Use list comprehensions for concise data transformation
  • Apply map(), filter(), and sorted() with custom keys
  • Chain multiple transformations in a pipeline

Starter Code

# Medium: Data Processing Pipeline

# Raw sales data: list of dicts
sales_data = [
{"product": "Laptop", "price": 1200, "quantity": 5, "region": "North"},
{"product": "Mouse", "price": 25, "quantity": 50, "region": "South"},
{"product": "Monitor", "price": 300, "quantity": 10, "region": "North"},
{"product": "Keyboard", "price": 80, "quantity": 30, "region": "East"},
{"product": "Headphones", "price": 150, "quantity": 15, "region": "West"},
{"product": "Tablet", "price": 400, "quantity": 8, "region": "South"},
]

# TODO 1: Use a list comprehension to calculate total_revenue for each item
# (revenue = price * quantity)

# TODO 2: Use filter() with lambda to get only items with revenue > 1000

# TODO 3: Use sorted() with a lambda key to sort by revenue descending

# TODO 4: Use a list comprehension to get all products from "North" region

# TODO 5: Use map() with a lambda to apply a 10% discount to all prices

# TODO 6: Calculate total revenue across all items using sum() and a gen expr

# TODO 7: Build a function pipeline(data, transforms) that chains all steps

# Your code here 👇

Expected Output

=== DATA PROCESSING PIPELINE ===

Step 1 — Revenue per item:
Laptop: $6000 | Mouse: $1250 | Monitor: $3000 | ...

Step 2 — High-revenue items (>$1000):
Laptop ($6000), Monitor ($3000), Mouse ($1250)

Step 3 — Sorted by revenue:
1. Laptop — $6000
2. Monitor — $3000
3. Mouse — $1250

Step 4 — North region products:
Laptop, Monitor

Step 5 — Prices after 10% discount:
[1080.0, 22.5, 270.0, 72.0, 135.0, 360.0]

Step 6 — Total revenue: $12,950.00

🏆 Hard: Modular Weather Report System

Time: 35 minutes

Build a modular weather report system that uses functions, modules (both built-in and custom), lambda, and comprehensions to fetch, process, and display weather data.

Learning Objectives

  • Organise code into multiple function files (simulated)
  • Use lambda and comprehensions for data transformation
  • Import and use standard library modules (random, datetime, statistics, textwrap)
  • Design a clean API surface with well-documented functions
  • Build a complete, extensible application

Starter Code

# Hard: Modular Weather Report System

import random
import datetime
from statistics import mean, median, stdev

# --- Simulated weather data generator ---
# (In a real app, this would come from an API)

def generate_weather_data(city, days=7):
"""Generate simulated daily weather readings for a city."""
data = []
for i in range(days):
date = (datetime.date.today() - datetime.timedelta(days=i)).isoformat()
temp = round(random.uniform(15, 35), 1)
humidity = random.randint(40, 90)
condition = random.choice(["Sunny", "Cloudy", "Rainy", "Windy"])
data.append({
"date": date,
"temp": temp,
"humidity": humidity,
"condition": condition,
})
return data

# TODO 1: Implement filter_by_condition(data, condition) using list comp
# TODO 2: Implement average_temps(data) — return avg, min, max temps
# TODO 3: Implement hottest_day(data) using max() with lambda key
# TODO 4: Implement temp_summary(data) — return mean, median, stdev using statistics module
# TODO 5: Implement format_report(data, city) — pretty print the full report
# TODO 6: Implement compare_cities(data1, name1, data2, name2) — side-by-side comparison

# Test with two cities
city_a = generate_weather_data("Mumbai", 7)
city_b = generate_weather_data("Delhi", 7)

# Your code here 👇

Expected Output

═══════════════════════════════════════
WEATHER REPORT — Mumbai
7-Day Summary
═══════════════════════════════════════

Date Temp Humidity Condition
───────────────────────────────────────
2025-01-15 28.3°C 72% Sunny ☀️
2025-01-14 31.0°C 65% Cloudy ⛅
...

───────────────────────────────────────
Temperature Stats:
Mean: 30.2°C
Median: 30.5°C
Std Dev: 2.1°C
Min: 27.1°C
Max: 34.0°C
───────────────────────────────────────
Hottest Day: 2025-01-12 (34.0°C, Sunny)

═══ CITY COMPARISON ═══
Mumbai Delhi
───────────────────────────────
Avg Temp 30.2°C 28.7°C
Avg Humidity 68% 52%
Rainy Days 2 1
Sunny Days 3 4
───────────────────────────────

💡 Tips for Success

  • One function, one job — if a function does two things, split it into two functions.
  • Docstrings are documentation — every function should have a """docstring""" explaining what it does, its parameters, and its return value.
  • Lambda is for simple operations — if the logic needs more than one expression, use a regular def.
  • List comprehensions are not always faster — they're for readability. If the comprehension becomes unreadable, use a regular loop.
  • Module imports go at the top — standard library first, then third-party, then your own.

← Back to Exercises