Chapter 5 Exercises: Python Essentials for Vibe Coders
These exercises are organized into five tiers following Bloom's taxonomy. Start with Tier 1 and work your way up. Solutions to selected coding exercises are provided in code/exercise-solutions.py.
Tier 1: Recall (Exercises 1-7)
Exercise 1: Type Identification
For each of the following values, identify the Python data type (int, float, str, bool, list, dict, tuple, set, or NoneType):
a = 42
b = 3.14
c = "hello"
d = True
e = [1, 2, 3]
f = {"key": "value"}
g = (1, 2)
h = {1, 2, 3}
i = None
j = 0
k = ""
l = []
Exercise 2: Operator Identification Match each operator to its description:
| Operator | Description |
|---|---|
== |
a. Floor division |
!= |
b. Equality comparison |
// |
c. Modulo (remainder) |
% |
d. Inequality comparison |
** |
e. Exponentiation |
is |
f. Identity comparison |
Exercise 3: Scope Rules Given the LEGB rule, identify what value will be printed in each case:
x = "global"
def func():
x = "local"
print(x)
func() # What prints here?
print(x) # What prints here?
Exercise 4: Comprehension Anatomy Break down the following list comprehension into its component parts (iterable, transformation, filter condition):
result = [x.upper() for x in words if len(x) > 3]
Exercise 5: Import Styles
Name three different ways to import the Path class from the pathlib module and describe when each style is most appropriate.
Exercise 6: Exception Hierarchy List five common Python exception types and give a one-sentence description of when each occurs.
Exercise 7: Dunder Method Matching Match each dunder method to its purpose:
| Method | Purpose |
|---|---|
__init__ |
a. String for developers/debugging |
__str__ |
b. Constructor/initializer |
__repr__ |
c. Called by len() |
__len__ |
d. Enables + operator |
__add__ |
e. Human-readable string |
__eq__ |
f. Enables == comparison |
Tier 2: Apply (Exercises 8-16)
Exercise 8: Temperature Converter
Write a function celsius_to_fahrenheit(celsius: float) -> float that converts Celsius to Fahrenheit. Include a docstring and a type hint. Then write a second function fahrenheit_to_celsius(fahrenheit: float) -> float. Test both with the values 0, 100, and 212.
Exercise 9: Word Counter
Write a function count_words(text: str) -> dict[str, int] that takes a string and returns a dictionary mapping each word (lowercased) to its count. Use the split() method. Test it with: "the cat sat on the mat the cat".
Exercise 10: List Filtering
Given the list numbers = [3, -1, 4, -1, 5, 9, -2, 6, 5, -3, 5], write list comprehensions to produce:
- A list of only the positive numbers
- A list of the absolute values of all numbers
- A list of squares of numbers greater than 3
Exercise 11: Dictionary Manipulation Given the following student records, write code to:
students = [
{"name": "Alice", "grade": 92},
{"name": "Bob", "grade": 85},
{"name": "Charlie", "grade": 78},
{"name": "Diana", "grade": 95},
{"name": "Eve", "grade": 88},
]
- Find the student with the highest grade
- Calculate the average grade
- Create a dictionary mapping names to grades
- Filter to only students with grades above 85
Exercise 12: File Operations
Write a function read_config(filepath: str) -> dict that reads a JSON configuration file and returns its contents as a dictionary. Include proper error handling for FileNotFoundError and json.JSONDecodeError. Use the with statement.
Exercise 13: Dataclass Creation
Create a Book dataclass with fields for title (str), author (str), year (int), isbn (str), and price (float). Add a method is_recent(self) -> bool that returns True if the book was published in the last 5 years. Create three instances and demonstrate using them.
Exercise 14: String Processing
Write a function clean_email(raw_email: str) -> str | None that:
- Strips leading/trailing whitespace
- Converts to lowercase
- Validates that it contains exactly one @ symbol and at least one . after the @
- Returns the cleaned email if valid, or None if invalid
Test with: " Alice@Example.COM ", "invalid-email", "two@@signs.com", "no-dot@example".
Exercise 15: Tuple Unpacking Given the following list of tuples representing (name, age, city), write code to:
people = [
("Alice", 30, "Portland"),
("Bob", 25, "Seattle"),
("Charlie", 35, "Portland"),
("Diana", 28, "Seattle"),
]
- Unpack and print each person's information
- Create a dictionary grouping people by city
- Find the oldest person using
max()with a key function
Exercise 16: Error Handling Practice
Write a function safe_divide(a, b) that:
- Returns the result of a / b
- Handles ZeroDivisionError by returning None
- Handles TypeError (e.g., if strings are passed) by raising a ValueError with a descriptive message
- Includes a docstring explaining the function's behavior
Tier 3: Analyze (Exercises 17-24)
Exercise 17: Code Review -- Spot the Issues The following AI-generated code has several issues. Identify all of them and explain why each is problematic:
import os
import sys
import json
import re
def processData(data):
result = []
for i in range(len(data)):
if data[i] != None:
item = data[i]
if type(item) == str:
result.append(item.upper())
elif type(item) == int:
result.append(item * 2)
file = open("output.txt", "w")
file.write(str(result))
return result
Exercise 18: Comprehension vs. Loop Analysis For each of the following, determine whether a list comprehension or a regular loop is more appropriate, and explain your reasoning:
- Filtering a list of 10 items based on a simple condition
- Processing items where each item requires a try/except block
- Building a list where the logic involves 3 nested loops
- Transforming a list of strings to uppercase
Exercise 19: Mutable Default Argument Explain what is wrong with this function and what will happen if you call it three times with no arguments:
def add_item(item, shopping_list=[]):
shopping_list.append(item)
return shopping_list
What is the correct way to write this function?
Exercise 20: Type Hint Analysis Review the following function signatures and identify any type hint issues:
def fetch_data(url: str) -> dict:
"""Fetch data from a URL. Returns None on failure."""
...
def process_items(items: list) -> list:
"""Process a list of strings and return a list of integers."""
...
def find_user(user_id: int) -> User:
"""Find a user by ID. Raises ValueError if not found."""
...
Exercise 21: Inheritance Design Analysis An AI assistant generated the following class hierarchy. Analyze whether this is a good design and explain any issues:
class Animal:
def __init__(self, name, sound, can_fly, can_swim, legs):
self.name = name
self.sound = sound
self.can_fly = can_fly
self.can_swim = can_swim
self.legs = legs
class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Woof", False, True, 4)
class Bird(Animal):
def __init__(self, name):
super().__init__(name, "Tweet", True, False, 2)
class Penguin(Bird):
def __init__(self, name):
super().__init__(name)
self.can_fly = False
self.can_swim = True
Exercise 22: Performance Analysis Analyze the performance characteristics of the following two implementations of a function that checks if a list contains any duplicates. Which is better and why?
# Version A
def has_duplicates_a(items):
for i in range(len(items)):
for j in range(i + 1, len(items)):
if items[i] == items[j]:
return True
return False
# Version B
def has_duplicates_b(items):
return len(items) != len(set(items))
Exercise 23: Module Organization Analysis An AI generated a single 500-line Python file with 15 functions, 3 classes, and various constants. What questions would you ask the AI to determine if the code should be split into multiple modules? What are the criteria for splitting?
Exercise 24: Pattern Recognition Identify the design pattern or Python idiom being used in each code snippet:
# Snippet A
result = value if value is not None else default
# Snippet B
handlers = {"save": save_func, "load": load_func, "delete": delete_func}
action = handlers.get(command, unknown_handler)
action(data)
# Snippet C
class DatabaseConnection:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
# Snippet D
def read_file(path):
if not path.exists():
return None
if not path.is_file():
return None
return path.read_text()
Tier 4: Create (Exercises 25-31)
Exercise 25: Contact Book
Create a ContactBook class that stores contacts as Contact dataclass instances (with name, email, phone, and optional notes). Implement methods to:
- Add a contact
- Remove a contact by name
- Search contacts by name (partial match, case-insensitive)
- Save all contacts to a JSON file
- Load contacts from a JSON file
- Display all contacts in a formatted table
Use type hints, docstrings, and proper error handling throughout.
Exercise 26: Log File Analyzer Write a function that reads a log file where each line has the format:
2025-01-15 10:30:45 ERROR Failed to connect to database
2025-01-15 10:31:00 INFO Server started successfully
Parse each line and return a dictionary with: - Count of each log level (INFO, WARNING, ERROR, CRITICAL) - List of all ERROR and CRITICAL messages - The time range covered by the log file
Exercise 27: CSV Processor
Write a module that reads a CSV file (without using the csv module -- practice string parsing), calculates summary statistics for numeric columns (min, max, mean, median), and writes the results to a new file. Handle edge cases like missing values and non-numeric data.
Exercise 28: Recipe Manager
Design and implement a Recipe class hierarchy:
- A Recipe dataclass with title, ingredients (list of tuples: name, quantity, unit), instructions (list of strings), prep_time, and cook_time
- A RecipeBook class that stores recipes and supports searching by ingredient, filtering by total time, and exporting to a formatted text file
- Proper type hints, docstrings, and error handling
Exercise 29: File Organizer
Write a script that takes a directory path and organizes files into subdirectories by file extension (e.g., .py files go into a python/ folder, .txt into text/, etc.). Use pathlib for all path operations. Include a dry-run mode that prints what would happen without actually moving files.
Exercise 30: Data Pipeline Create a simple data pipeline using generators: - A generator that reads lines from a file - A generator that filters lines based on a predicate - A generator that transforms lines (e.g., parsing CSV, extracting fields) - A function that chains these generators and processes the result
Demonstrate the pipeline by processing a sample data file.
Exercise 31: Simple Calculator with History Build a calculator module that: - Supports basic operations (+, -, , /, *) - Maintains a history of calculations as a list of named tuples - Can undo the last operation - Can save/load history to/from a JSON file - Uses proper error handling for division by zero and invalid input
Tier 5: Challenge (Exercises 32-35)
Exercise 32: AI Code Evaluator
Write a Python script that takes a Python file as input and performs basic code quality checks:
- Counts the number of functions and classes
- Checks if all functions have docstrings
- Checks if type hints are present on function parameters and return types
- Identifies functions longer than 20 lines
- Detects bare except clauses
- Reports unused imports (by simple heuristic: import name not found elsewhere in file)
This is essentially a simplified linter. Use only the standard library (no AST module required -- string parsing is fine for this exercise).
Exercise 33: Python to Pseudocode Translator Write a program that takes simple Python code as input and produces English pseudocode as output. Handle: - Variable assignments ("Set x to 5") - If/elif/else statements ("If x is greater than 10, then...") - For loops ("For each item in the list...") - Function definitions ("Define a function called X that takes Y") - Return statements ("Return the value of...")
This exercise builds the reverse skill of what AI assistants do: translating code to natural language.
Exercise 34: Multi-Chapter Integration -- Vibe Coding Simulator Create a simple text-based simulation of the vibe coding workflow: 1. The "user" enters a natural-language request (from a predefined list) 2. The "AI" generates Python code from templates (use dictionary-based template selection) 3. The "reviewer" (automated) checks the code for common issues 4. The system suggests improvements based on the review
This integrates concepts from Chapters 1-5: the vibe coding workflow (Ch 1), understanding AI limitations (Ch 2), tool usage (Ch 3), and Python knowledge (Ch 5).
Exercise 35: Standard Library Deep Dive
Choose three standard library modules not covered in detail in this chapter (suggestions: functools, contextlib, dataclasses, enum, typing, abc). For each:
1. Write a 200-word explanation of what the module does and when to use it
2. Create three practical code examples demonstrating different features
3. Identify at least one common mistake or pitfall when using the module
4. Explain how recognizing this module in AI-generated code helps you evaluate the code