3 Hours
16. Hands-On Mini Projects
Module 16: Mini Projects
Building things that actually work
Project 1 — Calculator Program
A complete command-line calculator with error handling:
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b):
if b == 0:
raise ValueError('Cannot divide by zero')
return a / b
operations = {'+': add, '-': subtract, '*': multiply, '/': divide}
def calculator():
print('Simple Calculator')
print('Operations: + - * /')
while True:
try:
a = float(input('First number (or q to quit): '))
op = input('Operation: ').strip()
b = float(input('Second number: '))
if op not in operations:
print('Unknown operation.')
continue
result = operations[op](a, b)
print(f'Result: {a} {op} {b} = {result}')
except ValueError as e:
print(f'Error: {e}')
except KeyboardInterrupt:
print('Goodbye!')
break
calculator()
Project 2 — To-Do List Application
A persistent to-do list that saves to a file:
import json
import os
FILE = 'todos.json'
def load_todos():
if os.path.exists(FILE):
with open(FILE, 'r') as f:
return json.load(f)
return []
def save_todos(todos):
with open(FILE, 'w') as f:
json.dump(todos, f, indent=2)
def show_todos(todos):
if not todos:
print('No tasks yet!')
return
for i, task in enumerate(todos, 1):
status = '[X]' if task['done'] else '[ ]'
print(f'{i}. {status} {task["text"]}')
todos = load_todos()
while True:
print('\n1=List 2=Add 3=Complete 4=Delete 5=Quit')
choice = input('Choose: ').strip()
if choice == '1':
show_todos(todos)
elif choice == '2':
text = input('New task: ')
todos.append({'text': text, 'done': False})
save_todos(todos)
elif choice == '3':
show_todos(todos)
n = int(input('Complete task #: ')) - 1
todos[n]['done'] = True
save_todos(todos)
elif choice == '4':
show_todos(todos)
n = int(input('Delete task #: ')) - 1
todos.pop(n)
save_todos(todos)
elif choice == '5':
break
Project 3 — Number Guessing Game
import random
def number_game(min_val=1, max_val=100, max_attempts=7):
secret = random.randint(min_val, max_val)
attempts = 0
print(f'Guess a number between {min_val} and {max_val}!')
print(f'You have {max_attempts} attempts.')
while attempts < max_attempts:
try:
guess = int(input(f'Attempt {attempts+1}/{max_attempts}: '))
except ValueError:
print('Enter a valid number.')
continue
attempts += 1
if guess < secret:
print('Too low!')
elif guess > secret:
print('Too high!')
else:
print(f'Correct! You got it in {attempts} attempt(s)!')
return
print(f'Game over! The number was {secret}.')
number_game()
Project 4 — Simple File-Based Project
import csv
def add_student(name, scores):
avg = sum(scores) / len(scores)
grade = 'A' if avg >= 90 else 'B' if avg >= 80 else 'C' if avg >= 70 else 'F'
with open('grades.csv', 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow([name, *scores, f'{avg:.1f}', grade])
print(f'Added {name} — Average: {avg:.1f} ({grade})')
def show_top_students(n=3):
with open('grades.csv', 'r') as f:
rows = list(csv.reader(f))
sorted_rows = sorted(rows, key=lambda r: float(r[-2]), reverse=True)
print(f'\nTop {n} Students:')
for row in sorted_rows[:n]:
print(f' {row[0]}: {row[-2]} ({row[-1]})')
add_student('Ama', [95, 88, 92, 90])
add_student('Kofi', [78, 82, 75, 80])
add_student('Abena', [99, 95, 98, 97])
show_top_students()
Knowledge Check
Ready to test your understanding of 16. Hands-On Mini Projects?