๐งช Practice: Power Tools
Comprehensions, generators, and modules โ the Module 10 toolkit, under pressure. Solutions at the bottom.
Exercise 1 โ Comprehension warmups
Rewrite each loop as a one-line comprehension:
# A
result = []
for n in range(1, 11):
if n % 2 == 0:
result.append(n * n)
# B
names = ["aarav", "diya", "kabir"]
caps = []
for n in names:
caps.append(n.upper())
# C
words = ["hi", "hello", "hey", "greetings"]
short = []
for w in words:
if len(w) <= 4:
short.append(w)Exercise 2 โ The data cleaner
Given this messy list, produce a clean list of proper-cased, stripped names โ one comprehension:
raw = [" aarav sharma ", "DIYA PATEL", " kabir singh ", "Meera IYER"]
# Expected: ['Aarav Sharma', 'Diya Patel', 'Kabir Singh', 'Meera Iyer']*(Hint: .title() capitalizes each word.)*
Exercise 3 โ Dict comprehension workout
From marks = {"Aarav": 92, "Diya": 45, "Kabir": 78, "Meera": 88}, build:
Exercise 4 โ The lazy sequence
Write a generator function even_numbers(limit) that yields even numbers from 0 up to limit. Loop it to print evens below 12.
Exercise 5 โ The module split
Create two files: utils.py containing a clean_name(name) function (strip + title-case), and main.py that imports it and processes this list:
raw = [" aarav ", "DIYA"]
# main.py prints: ['Aarav', 'Diya']Add the if __name__ == "__main__": guard to main.py properly.
Solutions
Exercise 1:
# A
result = [n * n for n in range(1, 11) if n % 2 == 0]
# B
caps = [n.upper() for n in names]
# C
short = [w for w in words if len(w) <= 4]Exercise 2:
clean = [name.strip().title() for name in raw]
print(clean)Exercise 3:
marks = {"Aarav": 92, "Diya": 45, "Kabir": 78, "Meera": 88}
passing = {name: m for name, m in marks.items() if m >= 50}
# {'Aarav': 92, 'Kabir': 78, 'Meera': 88}
results = {name: ("Pass" if m >= 50 else "Fail") for name, m in marks.items()}
# {'Aarav': 'Pass', 'Diya': 'Fail', 'Kabir': 'Pass', 'Meera': 'Pass'}
topper = max(marks, key=lambda name: marks[name])
# 'Aarav'Exercise 4:
def even_numbers(limit):
n = 0
while n < limit:
yield n
n += 2
for even in even_numbers(12):
print(even) # 0 2 4 6 8 10Exercise 5:
# utils.py
def clean_name(name):
return name.strip().title()# main.py
from utils import clean_name
def main():
raw = [" aarav ", "DIYA"]
clean = [clean_name(name) for name in raw]
print(clean) # ['Aarav', 'Diya']
if __name__ == "__main__":
main()โ Module 10 Checkpoint
Comprehensions compressing loops, generators streaming lazily, code split into modules. Your Python just became *Pythonic*.
Next module: The Ecosystem โ pip, environments, requests, and Git. Where your code meets the world.