Python Practice Programs
100 Exercises: Lists · Dictionaries · OOP
A hands-on collection of progressively challenging Python programs covering list manipulation,
dictionary operations, and object-oriented programming. Work through them in order for the best
learning curve.
Section Programs Topics
1 — Lists Basics #1 – #20 Append, slice, sort, search, comprehensions
2 — Dictionaries Basics #21 – #40 CRUD, nesting, iteration, merging
3 — Lists + Dicts Combined #41 – #60 Records, tables, frequency, grouping
4 — OOP Foundations #61 – #80 Classes, inheritance, encapsulation
5 — OOP + Lists & Dicts #81 – #100 Collections of objects, real-world systems
Section 1 — Lists Basics (#1 – #20)
#1 — Hello List
Create a list of names and print each one.
names = ["Elemson", "Mwila", "Chanda", "Bwalya"] for name in names: print(f"Hello, {name}!")
Tip: enumerate() gives you index + value at once.
#2 — List Length & Access
Access elements by index and get the length.
fruits = ["mango", "banana", "guava", "orange", "pawpaw"] print(f"Total fruits: {len(fruits)}")
print(f"First: {fruits[0]}") print(f"Last: {fruits[-1]}") print(f"Middle slice: {fruits[1:4]}")
#3 — Append & Remove
Dynamically add and remove items from a list.
items = ["pen", "book", "ruler"] [Link]("calculator") [Link](1, "eraser")
[Link]("ruler") print(items) print(f"Popped: {[Link]()}") print(items)
Tip: pop() removes and returns the last item (or by index).
#4 — List Sorting
Sort a list of numbers in ascending and descending order.
scores = [55, 92, 78, 45, 88, 63, 71] [Link]() print("Ascending:", scores)
[Link](reverse=True) print("Descending:", scores) print("Sorted copy:",
sorted([3,1,4,1,5,9])) # non-destructive
#5 — Finding Items
Search for items and their positions in a list.
animals = ["lion", "elephant", "zebra", "elephant", "giraffe"] print("elephant" in animals) # True
print([Link]("zebra")) # 2 print([Link]("elephant")) # 2 # Safe search target =
"hippo" if target in animals: print([Link](target)) else: print(f"{target} not found.")
#6 — List Math
Perform calculations on a numeric list.
nums = [4, 7, 2, 9, 1, 5, 8, 3, 6] print(f"Sum: {sum(nums)}") print(f"Min: {min(nums)}")
print(f"Max: {max(nums)}") print(f"Average: {sum(nums)/len(nums):.2f}") print(f"Sorted:
{sorted(nums)}")
#7 — List Comprehension — Squares
Generate squares of numbers using list comprehension.
squares = [x**2 for x in range(1, 11)] print(squares) evens = [x for x in range(1, 21) if x % 2 ==
0] print(evens) celsius = [0, 10, 20, 30, 40] fahrenheit = [(c * 9/5) + 32 for c in celsius]
print(fahrenheit)
Tip: List comprehensions are faster and more Pythonic than for-loops for building lists.
#8 — Flattening a Nested List
Flatten a 2D list into a single list.
matrix = [[1,2,3],[4,5,6],[7,8,9]] flat = [num for row in matrix for num in row] print(flat) #
Also works with extend flat2 = [] for row in matrix: [Link](row) print(flat2)
#9 — Removing Duplicates
Remove duplicates while preserving order.
data = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] seen = [] unique = [] for item in data: if item not in
seen: [Link](item) [Link](item) print(unique) # Fast alternative (doesn't preserve
order): print(list(set(data)))
#10 — Reversing a List
Reverse a list three different ways.
lst = [1, 2, 3, 4, 5] # Method 1: reverse() — in-place [Link]() print(lst) # Method 2:
slicing — returns new list original = [1, 2, 3, 4, 5] print(original[::-1]) # Method 3: reversed()
— iterator for item in reversed(original): print(item, end=" ")
#11 — Stack using a List
Simulate a stack (LIFO) using a list.
stack = [] [Link]("page1") # push [Link]("page2") [Link]("page3")
print("Stack:", stack) print("Top:", stack[-1]) print("Popped:", [Link]()) # LIFO print("Stack
after pop:", stack)
Tip: Stacks are used in browser history, undo systems, and call stacks.
#12 — Queue using a List
Simulate a queue (FIFO) using a list.
from collections import deque queue = deque() [Link]("customer1") [Link]("customer2")
[Link]("customer3") print("Queue:", list(queue)) served = [Link]() # FIFO
print(f"Served: {served}") print("Remaining:", list(queue))
#13 — Zip Two Lists
Pair up two lists element-by-element.
subjects = ["Maths", "Physics", "Chemistry"] marks = [95, 88, 91] for subject, mark in
zip(subjects, marks): print(f"{subject}: {mark}") # Create list of tuples pairs =
list(zip(subjects, marks)) print(pairs)
#14 — Enumerate
Use enumerate to get index and value together.
tasks = ["Wake up", "Exercise", "Study Python", "Eat", "Sleep"] print("Daily Routine:") for i,
task in enumerate(tasks, start=1): print(f" {i}. {task}")
#15 — List Slicing
Practice slicing lists in various ways.
lst = list(range(10)) # [0,1,2,3,4,5,6,7,8,9] print(lst[2:6]) # [2,3,4,5] print(lst[:4]) #
[0,1,2,3] print(lst[6:]) # [6,7,8,9] print(lst[::2]) # every 2nd: [0,2,4,6,8] print(lst[::-1]) #
reversed print(lst[1:8:3]) # [1,4,7]
#16 — Filter a List
Filter items from a list based on a condition.
grades = [55, 72, 48, 89, 63, 91, 40, 77] passed = [g for g in grades if g >= 50] failed = [g for g
in grades if g < 50] distinctions = [g for g in grades if g >= 80] print(f"Passed: {passed}")
print(f"Failed: {failed}") print(f"Distinctions: {distinctions}")
#17 — 2D List — Matrix
Create and traverse a 2D list (matrix).
rows, cols = 3, 3 matrix = [[i * cols + j + 1 for j in range(cols)] for i in range(rows)]
print("Matrix:") for row in matrix: print(row) print(f"Element at [1][2]: {matrix[1][2]}")
#18 — Merging & Copying Lists
Merge lists and understand shallow vs. reference copy.
a = [1, 2, 3] b = [4, 5, 6] merged = a + b print(merged) merged2 = [*a, *b] # unpacking
print(merged2) c = [Link]() # shallow copy [Link](99) print("a unchanged:", a) print("c
modified:", c)
#19 — Min/Max Without Built-ins
Find min and max manually to understand the logic.
nums = [34, 12, 89, 5, 67, 23, 91, 45] minimum = nums[0] maximum = nums[0] for n in nums[1:]: if n
< minimum: minimum = n if n > maximum: maximum = n print(f"Min: {minimum}, Max: {maximum}")
#20 — To-Do List App
A mini interactive to-do list manager.
tasks = [] def add(task): [Link]({"task": task, "done": False}) def complete(i):
tasks[i]["done"] = True def show(): for i, t in enumerate(tasks): status = "✓" if t["done"] else
"■" print(f" [{status}] {i}: {t['task']}") add("Study Python OOP") add("Practice forex demo")
add("Watch A Will Eternal") complete(0) show()
Tip: Storing dicts inside lists is the foundation of real-world data management.
Section 2 — Dictionaries Basics (#21 – #40)
#21 — Create & Access a Dict
Build a dictionary and access values by key.
student = { "name": "Elemson", "school": "Chilenje South High School", "grade": 12, "distinction":
True } print(student["name"]) print([Link]("age", "Not provided")) # safe access
print(list([Link]())) print(list([Link]()))
#22 — Add, Update & Delete
Modify a dictionary after creation.
profile = {"username": "mechatronics_guy", "level": 1} profile["email"] = "elemson@[Link]" #
add profile["level"] = 2 # update del profile["email"] # delete [Link]("level", None) # safe
delete print(profile)
#23 — Iterating a Dictionary
Loop through keys, values, and key-value pairs.
scores = {"Maths": 95, "Physics": 88, "Chemistry": 91, "English": 87} for key in scores:
print(key) for val in [Link](): print(val) for k, v in [Link](): print(f"{k}: {v}")
#24 — Dictionary Comprehension
Build dictionaries using comprehension syntax.
squares = {x: x**2 for x in range(1, 8)} print(squares) words = ["apple", "banana", "cherry"]
lengths = {w: len(w) for w in words} print(lengths) # Filter: only even squares even_sq = {x: x**2
for x in range(1,11) if x % 2 == 0} print(even_sq)
#25 — Counting with a Dict
Use a dictionary to count occurrences.
text = "mechatronics engineering is the best field" words = [Link]() count = {} for word in
words: count[word] = [Link](word, 0) + 1 print(count) # Most common word: most = max(count,
key=[Link]) print(f"Most common: '{most}' ({count[most]}x)")
#26 — Grouping with a Dict
Group items into categories using a dictionary.
students = [ ("Elemson", "Engineering"), ("Mwila", "Medicine"), ("Chanda", "Engineering"),
("Bwalya", "Law"), ("Mutale", "Medicine"), ("Nkonde", "Engineering"), ] faculties = {} for name,
faculty in students: [Link](faculty, []).append(name) for faculty, names in
[Link](): print(f"{faculty}: {names}")
#27 — Nested Dictionary
Work with a dictionary inside a dictionary.
school = { "Grade 12A": { "Elemson": {"Math": 95, "Physics": 88}, "Mwila": {"Math": 72, "Physics":
80}, } } for student, marks in school["Grade 12A"].items(): avg = sum([Link]()) / len(marks)
print(f"{student}: avg = {avg:.1f}")
#28 — Merging Dictionaries
Combine two dictionaries into one.
defaults = {"theme": "dark", "language": "en", "font": 14} user_prefs = {"language": "bem",
"font": 16} # Method 1: update() settings = [Link]() [Link](user_prefs)
print(settings) # Method 2: unpacking (Python 3.9+) merged = {**defaults, **user_prefs}
print(merged)
#29 — Inverting a Dictionary
Swap keys and values in a dictionary.
codes = {"ZM": "Zambia", "ZW": "Zimbabwe", "SA": "South Africa"} inverted = {v: k for k, v in
[Link]()} print(inverted) # Usage: look up country code by name print(inverted["Zambia"])
#30 — Dict as a Switch/Case
Replace if-elif chains with a dictionary.
def get_day(num): days = {1:"Monday",2:"Tuesday",3:"Wednesday",
4:"Thursday",5:"Friday",6:"Saturday",7:"Sunday"} return [Link](num, "Invalid day")
print(get_day(3)) print(get_day(7)) print(get_day(9))
Tip: Dict dispatch is faster and cleaner than long if-elif chains.
#31 — Phone Book
A simple contact manager using a dictionary.
phone_book = {} def add(name, number): phone_book[name] = number def find(name): return
phone_book.get(name, "Not found") def delete(name): phone_book.pop(name, None) def show(): for n,
p in sorted(phone_book.items()): print(f" {n}: {p}") add("Chanda", "0977111222") add("Bwalya",
"0966333444") add("Mutale", "0955555666") print(find("Chanda")) delete("Mutale") show()
#32 — Word Frequency from File String
Count word frequency and find top N words.
from collections import Counter text = ( "Engineering is the application of science and
mathematics. " "Mechatronics combines mechanical electrical and computer engineering. "
"Engineering requires strong mathematics and physics foundations." ).lower() words =
[[Link](".,") for w in [Link]()] freq = Counter(words) print("Top 5 words:") for word, count
in freq.most_common(5): print(f" {word}: {count}")
#33 — Currency Converter
Use a dict of exchange rates to convert currencies.
rates = {"USD": 1.0, "ZMW": 27.5, "CNY": 7.2, "EUR": 0.92} def convert(amount, from_curr,
to_curr): in_usd = amount / rates[from_curr] return in_usd * rates[to_curr] print(f"100 ZMW =
{convert(100,'ZMW','USD'):.2f} USD") print(f"50 USD = {convert(50,'USD','ZMW'):.2f} ZMW")
print(f"200 CNY = {convert(200,'CNY','EUR'):.2f} EUR")
#34 — Inventory Tracker
Track stock levels using a dictionary.
inventory = {"cement": 100, "iron_bars": 250, "bricks": 1000} def restock(item, qty):
inventory[item] = [Link](item, 0) + qty print(f"Restocked {qty} {item}. Total:
{inventory[item]}") def use(item, qty): if [Link](item, 0) >= qty: inventory[item] -= qty
print(f"Used {qty} {item}. Remaining: {inventory[item]}") else: print(f"Insufficient {item}!")
restock("cement", 50) use("iron_bars", 100) use("bricks", 1200)
#35 — Exam Results Dict
Store and analyze student exam results.
results = { "Elemson": [95, 88, 91, 87, 92], "Mwila": [72, 80, 68, 75, 70], "Chanda": [85, 79, 83,
88, 90], } for student, marks in [Link](): avg = sum(marks)/len(marks) grade =
"Distinction" if avg>=80 else "Credit" if avg>=65 else "Pass" print(f"{student}: avg={avg:.1f} —
{grade}")
#36 — Config File Simulation
Use a dict to simulate a configuration system.
config = { "debug": False, "max_retries": 3, "timeout": 30, "db_host": "localhost", "db_port":
5432, } def get_config(key, default=None): return [Link](key, default) def set_config(key,
value): config[key] = value print(f"Config updated: {key} = {value}") set_config("debug", True)
print(get_config("timeout")) print(get_config("api_key", "not_set"))
#37 — Leaderboard
Maintain a score-sorted leaderboard.
leaderboard = {} def add_score(player, score): if player not in leaderboard or score >
leaderboard[player]: leaderboard[player] = score add_score("Elemson", 4200) add_score("Mwila",
3800) add_score("Chanda", 5100) add_score("Elemson", 4900) # personal best update ranked =
sorted([Link](), key=lambda x: x[1], reverse=True) print("=== LEADERBOARD ===") for
rank, (player, score) in enumerate(ranked, 1): print(f" #{rank} {player}: {score}")
#38 — Voting System
Count votes and determine a winner.
candidates = ["Alice", "Bob", "Charlie"] votes =
["Alice","Bob","Alice","Charlie","Alice","Bob","Charlie","Alice","Bob","Alice"] tally = {c: 0 for
c in candidates} for vote in votes: if vote in tally: tally[vote] += 1 winner = max(tally,
key=[Link]) total = sum([Link]()) print("Results:") for c, v in [Link](): print(f"
{c}: {v} votes ({v/total*100:.1f}%)") print(f"Winner: {winner}!")
#39 — Roman Numeral Converter
Convert integers to Roman numerals using an ordered dict.
def to_roman(num): values = [ (1000,"M"),(900,"CM"),(500,"D"),(400,"CD"),
(100,"C"),(90,"XC"),(50,"L"),(40,"XL"), (10,"X"),(9,"IX"),(5,"V"),(4,"IV"),(1,"I") ] result = ""
for value, numeral in values: while num >= value: result += numeral num -= value return result for
n in [1, 4, 9, 14, 40, 90, 399, 2024]: print(f"{n} = {to_roman(n)}")
#40 — Menu-Driven Dict App
Use a dict to map user menu choices to functions.
def add(): print("Adding item...") def view(): print("Viewing items...") def delete():
print("Deleting item...") def quit_(): print("Goodbye!"); exit() menu = { "1": ("Add item", add),
"2": ("View items", view), "3": ("Delete item", delete), "4": ("Quit", quit_), } for key, (label,
_) in [Link](): print(f" {key}. {label}") choice = "2" # simulate user input if choice in
menu: menu[choice][1]()
Tip: Mapping choices to functions avoids messy if-elif chains.
Section 3 — Lists + Dicts Combined (#41 – #60)
#41 — List of Dicts — Student Records
Manage a list of student record dictionaries.
students = [ {"name": "Elemson", "age": 18, "gpa": 4.0}, {"name": "Mwila", "age": 19, "gpa": 3.5},
{"name": "Chanda", "age": 18, "gpa": 3.8}, ] # Sort by GPA [Link](key=lambda s: s["gpa"],
reverse=True) for s in students: print(f"{s['name']}: GPA {s['gpa']}")
#42 — Filter Records
Filter a list of dicts by a condition.
products = [ {"name": "Laptop", "price": 8500, "in_stock": True}, {"name": "Phone", "price": 3200,
"in_stock": False}, {"name": "Tablet", "price": 4100, "in_stock": True}, {"name": "Watch",
"price": 1800, "in_stock": True}, ] available = [p for p in products if p["in_stock"]] affordable
= [p for p in available if p["price"] < 5000] for p in affordable: print(f"{p['name']}:
K{p['price']}")
#43 — Group by Category
Group a list of dicts by a category field.
items = [ {"name": "Python Book", "category": "Books"}, {"name": "Forex Journal", "category":
"Books"}, {"name": "USB Cable", "category": "Electronics"}, {"name": "Headphones", "category":
"Electronics"}, {"name": "Notebook", "category": "Stationery"}, ] grouped = {} for item in items:
cat = item["category"] [Link](cat, []).append(item["name"]) for cat, names in
[Link](): print(f"{cat}: {names}")
#44 — Dict of Lists — Timetable
Store a weekly timetable as a dict of lists.
timetable = { "Monday": ["Maths", "Physics", "Chemistry"], "Tuesday": ["English", "Biology",
"Maths"], "Wednesday": ["Physics", "Chemistry", "English"], "Thursday": ["Maths", "Biology",
"Physics"], "Friday": ["Chemistry", "English", "Maths"], } for day, subjects in [Link]():
print(f"{day}: {', '.join(subjects)}") # Find days with Maths maths_days = [d for d, s in
[Link]() if "Maths" in s] print(f"Maths days: {maths_days}")
#45 — CSV-Style Data Processing
Process tabular data stored as a list of dicts.
data = [ {"city": "Lusaka", "pop": 3360000, "province": "Lusaka"}, {"city": "Kitwe", "pop":
522000, "province": "Copperbelt"}, {"city": "Ndola", "pop": 451246, "province": "Copperbelt"},
{"city": "Livingstone","pop": 134019, "province": "Southern"}, ] total_pop = sum(d["pop"] for d in
data) print(f"Total: {total_pop:,}") largest = max(data, key=lambda x: x["pop"]) print(f"Largest:
{largest['city']}") cb = [d for d in data if d["province"] == "Copperbelt"] print(f"Copperbelt
cities: {[d['city'] for d in cb]}")
#46 — Frequency Counter
Count how often each item appears.
responses = ["yes","no","yes","maybe","yes","no","yes","no","maybe","yes"] freq = {} for r in
responses: freq[r] = [Link](r, 0) + 1 total = len(responses) for response, count in
sorted([Link](), key=lambda x:-x[1]): bar = "#" * count print(f"{response:6}: {bar}
({count/total*100:.0f}%)")
#47 — Matrix Operations
Add and multiply matrices represented as lists.
def mat_add(A, B): return [[A[i][j]+B[i][j] for j in range(len(A[0]))] for i in range(len(A))] def
mat_mul(A, B): rows, cols, inner = len(A), len(B[0]), len(B) return [[sum(A[i][k]*B[k][j] for k in
range(inner)) for j in range(cols)] for i in range(rows)] A = [[1,2],[3,4]] B = [[5,6],[7,8]]
print("Sum:", mat_add(A, B)) print("Product:", mat_mul(A, B))
#48 — Shopping Cart
Build a shopping cart with list and dict.
cart = [] def add_item(name, price, qty=1): for item in cart: if item["name"] == name: item["qty"]
+= qty; return [Link]({"name": name, "price": price, "qty": qty}) def total(): return
sum(i["price"] * i["qty"] for i in cart) add_item("Python Textbook", 250, 1) add_item("USB Drive",
180, 2) add_item("Python Textbook", 250, 1) # adds to existing for i in cart: print(f"{i['name']}
x{i['qty']}: K{i['price']*i['qty']}") print(f"Total: K{total()}")
#49 — Top N Items
Extract the top N records from a list of dicts.
scores = [ {"name":"Elemson","score":97},{"name":"Mwila","score":83},
{"name":"Chanda","score":91},{"name":"Bwalya","score":75},
{"name":"Mutale","score":88},{"name":"Nkonde","score":95}, ] top3 = sorted(scores, key=lambda x:
x["score"], reverse=True)[:3] print("Top 3:") for rank, s in enumerate(top3, 1): print(f" #{rank}
{s['name']}: {s['score']}")
#50 — Data Aggregation
Aggregate and summarize data from a list of dicts.
sales = [ {"month":"Jan","revenue":45000,"costs":32000},
{"month":"Feb","revenue":52000,"costs":35000}, {"month":"Mar","revenue":48000,"costs":31000},
{"month":"Apr","revenue":61000,"costs":40000}, ] for s in sales: s["profit"] = s["revenue"] -
s["costs"] s["margin"] = s["profit"] / s["revenue"] * 100 best = max(sales, key=lambda x:
x["profit"]) print(f"Best month: {best['month']} — profit K{best['profit']:,}") avg_margin =
sum(s["margin"] for s in sales) / len(sales) print(f"Avg margin: {avg_margin:.1f}%")
#51 — Graph as Adjacency List
Represent a graph using a dict of lists.
graph = { "Lusaka": ["Kabwe", "Livingstone", "Chipata"], "Kabwe": ["Lusaka", "Ndola"], "Ndola":
["Kabwe", "Kitwe"], "Kitwe": ["Ndola"], "Livingstone":["Lusaka"], "Chipata": ["Lusaka"], } city =
"Lusaka" print(f"{city} connects to: {graph[city]}") # Count connections for c, neighbors in
sorted([Link]()): print(f" {c}: {len(neighbors)} connection(s)")
#52 — Running Average
Compute a running/cumulative average of readings.
readings = [23.5, 24.1, 22.8, 25.0, 24.7, 23.9, 26.1] history = [] for r in readings:
[Link](r) avg = sum(history) / len(history) print(f"Reading: {r:.1f} | Running avg:
{avg:.2f}")
#53 — Pivot Table
Summarize list data by two dimensions.
sales = [ {"region":"North","product":"Cement","qty":200},
{"region":"South","product":"Cement","qty":150}, {"region":"North","product":"Bricks","qty":500},
{"region":"South","product":"Bricks","qty":300}, {"region":"North","product":"Cement","qty":100},
] pivot = {} for s in sales: r, p = s["region"], s["product"] [Link](r, {}) pivot[r][p]
= pivot[r].get(p, 0) + s["qty"] for region, products in [Link](): print(f"{region}:
{products}")
#54 — Anagram Checker
Check if two words are anagrams using dicts.
def char_count(word): count = {} for ch in [Link](): if [Link](): count[ch] =
[Link](ch, 0) + 1 return count def is_anagram(w1, w2): return char_count(w1) == char_count(w2)
pairs = [("listen","silent"),("hello","world"),("dusty","study")] for a, b in pairs: result =
"YES" if is_anagram(a,b) else "NO" print(f"{a} / {b}: anagram? {result}")
#55 — Grade Book
Full grade book: add, update, report.
gradebook = {} def add_student(name, marks): gradebook[name] = marks def update_mark(name,
subject, mark): if name in gradebook: gradebook[name][subject] = mark def report(name): marks =
[Link](name, {}) avg = sum([Link]())/len(marks) if marks else 0 print(f"{name}:
{marks} | Avg: {avg:.1f}") add_student("Elemson", {"Math":95,"Phy":88,"Chem":91})
add_student("Mwila", {"Math":72,"Phy":80,"Chem":68}) update_mark("Elemson", "Math", 98) for name
in gradebook: report(name)
#56 — Merge & Deduplicate Records
Merge two lists of records and remove duplicates by ID.
list1 = [{"id":1,"name":"Elemson"},{"id":2,"name":"Mwila"}] list2 =
[{"id":2,"name":"Mwila"},{"id":3,"name":"Chanda"}] merged = {r["id"]: r for r in list1 + list2} #
later record wins result = list([Link]()) for r in result: print(r)
#57 — Time Series Analysis
Find trends in a time-ordered dict.
prices = { "2024-01": 27.2, "2024-02": 27.5, "2024-03": 27.8, "2024-04": 28.1, "2024-05": 28.9,
"2024-06": 29.3, } months = list([Link]()) vals = list([Link]()) changes =
[(months[i], vals[i]-vals[i-1]) for i in range(1,len(vals))] print("Monthly ZMW/USD changes:") for
month, change in changes: arrow = "▲" if change > 0 else "▼" print(f" {month}: {arrow}
{abs(change):.2f}")
#58 — Simple Cache
Implement a basic memoization cache with a dict.
cache = {} def expensive_calc(n): if n in cache: print(f" [cache hit] {n}") return cache[n]
print(f" [computing] {n}") result = sum(range(n+1)) # simulate work cache[n] = result return
result for val in [100, 200, 100, 300, 200]: print(f"sum(0..{val}) = {expensive_calc(val)}")
Tip: This pattern is called memoization — huge speedup for repeated calls.
#59 — Language Translator
Build a mini dictionary-based translator.
dictionary = { "en": {"hello":"hello","water":"water","thank you":"thank you"},
"bem":{"hello":"shani","water":"amenshi","thank you":"natotela"},
"nya":{"hello":"moni","water":"madzi","thank you":"zikomo"}, } def translate(phrase,
from_lang="en", to_lang="bem"): eng = {v:k for k,v in dictionary[from_lang].items()}.get(phrase,
phrase) return dictionary[to_lang].get(eng, f"[no translation for '{phrase}']")
print(translate("hello", "en", "bem")) print(translate("thank you", "en", "nya"))
print(translate("amenshi", "bem","en"))
#60 — Data Pipeline
Chain list/dict operations to process raw data.
raw = [ " elemson, 18, engineering ", " mwila, 19, medicine ", " chanda, 18, law ", ] # Step 1:
clean cleaned = [[Link]() for r in raw] # Step 2: parse parsed =
[dict(zip(["name","age","field"], [Link](", "))) for r in cleaned] # Step 3: transform for p in
parsed: p["age"] = int(p["age"]) p["name"] = p["name"].title() # Step 4: filter engineers = [p for
p in parsed if p["field"] == "engineering"] print(f"Cleaned records: {len(parsed)}")
print(f"Engineers: {engineers}")
Section 4 — OOP Foundations (#61 – #80)
#61 — Your First Class
Define a simple class with attributes and methods.
class Student: def __init__(self, name, age): [Link] = name [Link] = age def greet(self):
print(f"Hi, I am {[Link]}, age {[Link]}.") def __str__(self): return f"Student({[Link]},
{[Link]})" s = Student("Elemson", 18) [Link]() print(s)
Tip: __str__ controls what print(object) shows — always define it.
#62 — Class Methods & Class Variables
Understand the difference between instance and class data.
class Counter: count = 0 # class variable, shared by all instances def __init__(self, name):
[Link] = name [Link] += 1 @classmethod def total(cls): return [Link] c1 =
Counter("Alpha") c2 = Counter("Beta") c3 = Counter("Gamma") print(f"Total counters created:
{[Link]()}")
#63 — Encapsulation
Use private attributes and getters/setters.
class BankAccount: def __init__(self, owner, balance=0): [Link] = owner self.__balance =
balance # private def deposit(self, amount): if amount > 0: self.__balance += amount def
withdraw(self, amount): if 0 < amount <= self.__balance: self.__balance -= amount else:
print("Insufficient funds.") @property def balance(self): return self.__balance acc =
BankAccount("Elemson", 1000) [Link](500) [Link](200) print(f"Balance: K{[Link]}")
Tip: Use @property instead of get_x() methods — it's more Pythonic.
#64 — Inheritance
Create a subclass that extends a parent class.
class Animal: def __init__(self, name): [Link] = name def speak(self): return "..." def
__str__(self): return f"{self.__class__.__name__}({[Link]})" class Dog(Animal): def
speak(self): return "Woof!" class Cat(Animal): def speak(self): return "Meow!" class Cow(Animal):
def speak(self): return "Moo!" animals = [Dog("Rex"), Cat("Luna"), Cow("Bessie")] for a in
animals: print(f"{a}: {[Link]()}")
#65 — Polymorphism
Different classes respond to the same method differently.
class Shape: def area(self): return 0 def describe(self): print(f"{self.__class__.__name__}: area
= {[Link]():.2f}") class Circle(Shape): def __init__(self, r): self.r = r def area(self):
return 3.14159 * self.r ** 2 class Rectangle(Shape): def __init__(self, w, h): self.w = w; self.h
= h def area(self): return self.w * self.h class Triangle(Shape): def __init__(self, b, h): self.b
= b; self.h = h def area(self): return 0.5 * self.b * self.h shapes = [Circle(5), Rectangle(4,6),
Triangle(3,8)] for s in shapes: [Link]()
#66 — Static Methods
Use @staticmethod for utility functions inside a class.
class MathUtils: @staticmethod def is_prime(n): if n < 2: return False for i in range(2,
int(n**0.5)+1): if n % i == 0: return False return True @staticmethod def factorial(n): if n == 0:
return 1 return n * [Link](n-1) @staticmethod def fibonacci(n): a, b = 0, 1 for _ in
range(n): a, b = b, a+b return a print(MathUtils.is_prime(97)) print([Link](6))
print([Link](10))
#67 — Abstract Classes
Enforce a method interface using ABC.
from abc import ABC, abstractmethod class Vehicle(ABC): def __init__(self, make, model): [Link]
= make [Link] = model @abstractmethod def fuel_type(self): pass @abstractmethod def
max_speed(self): pass def info(self): print(f"{[Link]} {[Link]}: " f"{self.fuel_type()},
max {self.max_speed()} km/h") class Car(Vehicle): def fuel_type(self): return "Petrol" def
max_speed(self): return 180 class ElectricBike(Vehicle): def fuel_type(self): return "Electric"
def max_speed(self): return 90 Car("Toyota","Corolla").info() ElectricBike("Zero","SR/F").info()
#68 — Dunder Methods
Implement magic methods to make objects behave like built-ins.
class Vector: def __init__(self, x, y): self.x = x; self.y = y def __add__(self, other): return
Vector(self.x+other.x, self.y+other.y) def __mul__(self, scalar): return Vector(self.x*scalar,
self.y*scalar) def __len__(self): return int((self.x**2 + self.y**2)**0.5) def __repr__(self):
return f"Vector({self.x}, {self.y})" v1 = Vector(2, 3) v2 = Vector(1, 4) print(v1 + v2) print(v1 *
3) print(len(v1))
#69 — Composition over Inheritance
Build complex objects by combining simpler ones.
class Engine: def __init__(self, horsepower): [Link] = horsepower def start(self): print(f"Engine
({[Link]}hp) started.") class GPS: def navigate(self, dest): print(f"Navigating to {dest}...")
class Car: def __init__(self, make, hp): [Link] = make [Link] = Engine(hp) [Link] =
GPS() def drive(self, dest): [Link]() [Link](dest) print(f"{[Link]} is on
its way!") car = Car("Toyota", 150) [Link]("Copperbelt University")
#70 — Dataclass
Use @dataclass for clean, boilerplate-free classes.
from dataclasses import dataclass, field @dataclass class Student: name: str age: int grades: list
= field(default_factory=list) def average(self): return sum([Link])/len([Link]) if
[Link] else 0 def add_grade(self, g): [Link](g) s = Student("Elemson", 18)
s.add_grade(95); s.add_grade(88); s.add_grade(91) print(s) print(f"Average: {[Link]():.1f}")
Tip: @dataclass auto-generates __init__, __repr__, and __eq__.
#71 — Iterator Class
Make a class iterable using __iter__ and __next__.
class Countdown: def __init__(self, start): [Link] = start def __iter__(self): return self
def __next__(self): if [Link] < 0: raise StopIteration val = [Link] [Link] -= 1
return val for num in Countdown(5): print(num, end=" ") print() print(list(Countdown(10)))
#72 — Context Manager
Implement __enter__ and __exit__ for resource management.
class FileLogger: def __init__(self, filename): [Link] = filename [Link] = [] def
__enter__(self): print(f"Opening {[Link]}") return self def write(self, msg):
[Link](msg) def __exit__(self, exc_type, exc_val, exc_tb): print(f"Closing
{[Link]}. Wrote {len([Link])} entries.") return False # don't suppress exceptions with
FileLogger("[Link]") as logger: [Link]("App started") [Link]("User logged in")
#73 — Mixin Classes
Add reusable behavior using mixin classes.
class TimestampMixin: def created_at(self): return "2025-01-01" class SerializeMixin: def
to_dict(self): return self.__dict__ class LogMixin: def log(self): print(f"[LOG]
{self.__class__.__name__}: {self.__dict__}") class User(TimestampMixin, SerializeMixin, LogMixin):
def __init__(self, name, email): [Link] = name [Link] = email u = User("Elemson",
"e@[Link]") print(u.created_at()) print(u.to_dict()) [Link]()
#74 — Class Decorator
Use a class as a decorator to add behavior.
class retry: def __init__(self, times=3): [Link] = times def __call__(self, func): def
wrapper(*args, **kwargs): for attempt in range(1, [Link]+1): try: return func(*args, **kwargs)
except Exception as e: print(f"Attempt {attempt} failed: {e}") print("All attempts failed.")
return wrapper @retry(times=3) def unstable_connection(url): raise ConnectionError("Timeout")
unstable_connection("[Link]
#75 — Property with Validation
Use @property setters to validate data on assignment.
class Temperature: def __init__(self, celsius=0): [Link] = celsius # triggers setter
@property def celsius(self): return self._celsius @[Link] def celsius(self, value): if
value < -273.15: raise ValueError("Below absolute zero!") self._celsius = value @property def
fahrenheit(self): return self._celsius * 9/5 + 32 t = Temperature(25) print(f"{[Link]}°C =
{[Link]}°F") [Link] = 100 print(f"{[Link]}°C = {[Link]}°F")
#76 — Singleton Pattern
Ensure only one instance of a class is created.
class Config: _instance = None def __new__(cls): if cls._instance is None: cls._instance =
super().__new__(cls) cls._instance.settings = {} return cls._instance def set(self, k, v):
[Link][k] = v def get(self, k): return [Link](k) c1 = Config() c2 = Config()
[Link]("theme", "dark") print([Link]("theme")) # "dark" — same object print(c1 is c2) # True
Tip: The Singleton is one of the most commonly used design patterns.
#77 — Observer Pattern
Implement a simple event/observer system.
class EventEmitter: def __init__(self): self._listeners = {} def on(self, event, callback):
self._listeners.setdefault(event, []).append(callback) def emit(self, event, *args): for cb in
self._listeners.get(event, []): cb(*args) emitter = EventEmitter() [Link]("login", lambda u:
print(f"Welcome, {u}!")) [Link]("login", lambda u: print(f"Logging login for {u}..."))
[Link]("logout", lambda u: print(f"Goodbye, {u}.")) [Link]("login", "Elemson")
[Link]("logout", "Elemson")
#78 — Factory Pattern
Use a factory function to create different class instances.
class Dog: def sound(self): return "Woof" class Cat: def sound(self): return "Meow" class Bird:
def sound(self): return "Tweet" def animal_factory(animal_type): animals = {"dog": Dog, "cat":
Cat, "bird": Bird} cls = [Link](animal_type.lower()) if cls: return cls() raise
ValueError(f"Unknown animal: {animal_type}") for kind in ["dog", "cat", "bird"]: a =
animal_factory(kind) print(f"{kind}: {[Link]()}")
#79 — Stack Class with OOP
Implement a Stack data structure as a class.
class Stack: def __init__(self): self._data = [] def push(self, item): self._data.append(item) def
pop(self): if self.is_empty(): raise IndexError("Stack is empty") return self._data.pop() def
peek(self): return self._data[-1] if self._data else None def is_empty(self): return
len(self._data) == 0 def __len__(self): return len(self._data) def __repr__(self): return
f"Stack({self._data})" s = Stack() [Link](10); [Link](20); [Link](30) print(s) print("Peek:",
[Link]()) print("Pop:", [Link]()) print(s)
#80 — Linked List
Implement a singly linked list from scratch.
class Node: def __init__(self, data): [Link] = data [Link] = None class LinkedList: def
__init__(self): [Link] = None def append(self, data): new = Node(data) if not [Link]:
[Link] = new; return cur = [Link] while [Link]: cur = [Link] [Link] = new def
__str__(self): result, cur = [], [Link] while cur: [Link](str([Link])); cur = [Link]
return " -> ".join(result) ll = LinkedList() for val in [10, 20, 30, 40]: [Link](val) print(ll)
Tip: Linked lists are a fundamental data structure — great for interviews.
Section 5 — OOP + Lists & Dicts (#81 – #100)
#81 — Student Registry
A class that manages a list of student objects.
class Student: def __init__(self, name, gpa): [Link] = name; [Link] = gpa def __repr__(self):
return f"{[Link]}({[Link]})" class Registry: def __init__(self): [Link] = [] def
enroll(self, name, gpa): [Link](Student(name, gpa)) def top(self, n=3): return
sorted([Link], key=lambda s: [Link], reverse=True)[:n] def average(self): return sum([Link]
for s in [Link]) / len([Link]) r = Registry() for name, gpa in
[("Elemson",4.0),("Mwila",3.5),("Chanda",3.8),("Bwalya",3.2)]: [Link](name, gpa) print("Top 3:",
[Link]()) print(f"Avg GPA: {[Link]():.2f}")
#82 — Library System
Manage a library of books using OOP.
class Book: def __init__(self, title, author, available=True): [Link] = title; [Link] =
author; [Link] = available def __repr__(self): return f'"{[Link]}" by {[Link]}'
class Library: def __init__(self): self._books = [] def add(self, title, author):
self._books.append(Book(title, author)) def borrow(self, title): for b in self._books: if
[Link]==title and [Link]: [Link]=False; print(f"Borrowed: {b}"); return
print(f"'{title}' not available.") def return_book(self, title): for b in self._books: if
[Link]==title: [Link]=True; print(f"Returned: {b}"); return def available(self): return [b
for b in self._books if [Link]] lib = Library() [Link]("Clean Code","Robert Martin")
[Link]("Python Crash Course","Eric Matthes") [Link]("Clean Code") [Link]("Clean Code") #
should say not available lib.return_book("Clean Code") print("Available:", [Link]())
#83 — Hospital Ward
Track patients in a hospital ward.
class Patient: def __init__(self, pid, name, condition): [Link] = pid; [Link] = name;
[Link] = condition [Link] = [] def prescribe(self, med):
[Link](med) def __repr__(self): return f"Patient({[Link]}: {[Link]})" class
Ward: def __init__(self, name): [Link] = name; [Link] = {} def admit(self, patient):
[Link][[Link]] = patient def discharge(self, pid): return [Link](pid, None)
def find(self, pid): return [Link](pid) def census(self): print(f"{[Link]}:
{len([Link])} patients") w = Ward("General") p1 = Patient(1001, "Elemson", "Observation")
[Link]("Paracetamol") [Link](p1) [Link]() print([Link](1001))
print([Link](1001).medications)
#84 — Forex Trade Journal
Track forex trades using OOP.
from datetime import date class Trade: def __init__(self, pair, direction, entry, exit_price,
size=1): [Link] = pair; [Link] = direction [Link] = entry; self.exit_price =
exit_price; [Link] = size [Link] = [Link]() [Link] = (exit_price-entry)*size if
direction=="buy" else (entry-exit_price)*size def __repr__(self): result = "WIN" if [Link] > 0
else "LOSS" return f"{[Link]} {[Link]}: PnL={[Link]:.2f} [{result}]" class Journal:
def __init__(self): [Link] = [] def add(self, *args): [Link](Trade(*args)) def
summary(self): wins = [t for t in [Link] if [Link] > 0] total = sum([Link] for t in
[Link]) print(f"Trades: {len([Link])} | Wins: {len(wins)} | Total PnL: {total:.2f}") j =
Journal() [Link]("V25","buy", 1200.5, 1215.3) [Link]("V25","sell", 1215.3, 1200.0)
[Link]("V25","buy", 1195.0, 1210.8) for t in [Link]: print(t) [Link]()
#85 — CBU Course Manager
Model a university course registration system.
class Course: def __init__(self, code, name, credits): [Link] = code; [Link] = name;
[Link] = credits def __repr__(self): return f"{[Link]}: {[Link]} ({[Link]} cr)"
class Student: def __init__(self, name): [Link] = name; [Link] = [] def enroll(self,
course): [Link](course) def drop(self, code): [Link] = [c for c in [Link]
if [Link] != code] def total_credits(self): return sum([Link] for c in [Link]) def
transcript(self): print(f"--- {[Link]}'s Courses ---") for c in [Link]: print(f" {c}")
print(f" Total credits: {self.total_credits()}") s = Student("Elemson")
[Link](Course("MCE101","Intro to Mechatronics",3)) [Link](Course("EEE102","Circuit Theory",4))
[Link](Course("MAT101","Engineering Maths",4)) [Link]() [Link]("EEE102") [Link]()
#86 — Inventory OOP System
Full inventory system with OOP patterns.
class Product: def __init__(self, pid, name, price, qty=0): [Link] = pid; [Link] = name;
[Link] = price; [Link] = qty def value(self): return [Link] * [Link] def
__repr__(self): return f"{[Link]}(qty={[Link]},K{[Link]})" class Inventory: def
__init__(self): self._products = {} def add_product(self, product): self._products[[Link]] =
product def restock(self, pid, qty): self._products[pid].qty += qty def sell(self, pid, qty): p =
self._products.get(pid) if p and [Link] >= qty: [Link] -= qty; return [Link] * qty return 0 def
total_value(self): return sum([Link]() for p in self._products.values()) def low_stock(self,
threshold=5): return [p for p in self._products.values() if [Link] <= threshold] inv = Inventory()
inv.add_product(Product(1,"Cement",450,100)) inv.add_product(Product(2,"Nails", 25, 4))
[Link](1, 50) print(f"Sold: K{[Link](1, 20)}") print(f"Total value:
K{inv.total_value():,}") print(f"Low stock: {inv.low_stock()}")
#87 — Chat App Simulation
Model a simple chat room with OOP.
class Message: def __init__(self, sender, text): [Link] = sender; [Link] = text def
__repr__(self): return f"[{[Link]}]: {[Link]}" class ChatRoom: def __init__(self, name):
[Link] = name; [Link] = []; [Link] = set() def join(self, user):
[Link](user) def send(self, sender, text): if sender in [Link]:
[Link](Message(sender, text)) def history(self, n=5): print(f"--- #{[Link]} (last
{n}) ---") for m in [Link][-n:]: print(f" {m}") room = ChatRoom("python-devs")
[Link]("Elemson"); [Link]("Mwila") [Link]("Elemson", "OOP is clicking now!")
[Link]("Mwila", "Same! Lists inside classes are ■") [Link]("Elemson", "Next up: Django")
[Link]()
#88 — Bank System
Multi-account bank with transactions history.
class Transaction: def __init__(self, t_type, amount): self.t_type = t_type; [Link] = amount
def __repr__(self): return f"{self.t_type}: K{[Link]:.2f}" class Account: def __init__(self,
acc_no, owner, balance=0): self.acc_no = acc_no; [Link] = owner self._balance = balance;
[Link] = [] def deposit(self, amount): self._balance += amount
[Link](Transaction("DEP", amount)) def withdraw(self, amount): if amount <=
self._balance: self._balance -= amount [Link](Transaction("WDR", amount)) else:
print("Insufficient funds.") @property def balance(self): return self._balance def
statement(self): print(f"Account {self.acc_no} — {[Link]}: K{[Link]:.2f}") for t in
[Link][-5:]: print(f" {t}") class Bank: def __init__(self): [Link] = {} def
open(self, owner, initial=0): acc_no = 1000 + len([Link]) acc = Account(acc_no, owner,
initial) [Link][acc_no] = acc; return acc bank = Bank() a = [Link]("Elemson", 5000)
[Link](2000); [Link](800); [Link](10000) [Link]()
#89 — RPG Character System
Build RPG characters with OOP.
class Character: def __init__(self, name, char_class, hp, attack): [Link] = name;
self.char_class = char_class [Link] = hp; self.max_hp = hp; [Link] = attack [Link] =
[]; [Link] = 1 def is_alive(self): return [Link] > 0 def take_damage(self, dmg): [Link] =
max(0, [Link] - dmg) def heal(self, amount): [Link] = min(self.max_hp, [Link] + amount) def
pick_up(self, item): [Link](item) def status(self): print(f"{[Link]}
[{self.char_class}] Lv{[Link]} " f"HP:{[Link]}/{self.max_hp} | Inv:{[Link]}") def
battle(a, b): print(f"=== {[Link]} vs {[Link]} ===") while a.is_alive() and b.is_alive():
b.take_damage([Link]); a.take_damage([Link]) winner = a if a.is_alive() else b print(f"Winner:
{[Link]}!") hero = Character("Elemson","Mechatronist",100,25) villain= Character("Rust",
"Bug", 80,20) hero.pick_up("Python Tome") [Link]() battle(hero, villain)
#90 — Task Queue
Priority task queue using OOP and lists.
class Task: PRIORITIES = {"high":1,"medium":2,"low":3} def __init__(self, name,
priority="medium"): [Link] = name; [Link] = priority def __repr__(self): return
f"[{[Link]()}] {[Link]}" class TaskQueue: def __init__(self): self._tasks = [] def
add(self, name, priority="medium"): self._tasks.append(Task(name, priority))
self._tasks.sort(key=lambda t: [Link][[Link]]) def next(self): return
self._tasks.pop(0) if self._tasks else None def show(self): print("Queue:"); [print(f" {t}") for t
in self._tasks] q = TaskQueue() [Link]("Submit CBU application","high") [Link]("Watch Python
tutorial","low") [Link]("Practice forex demo","medium") [Link]("Fix Python bug","high") [Link]()
print(f"Next: {[Link]()}")
#91 — Plugin System
Use a dict registry to build a plugin architecture.
class PluginManager: def __init__(self): self._plugins = {} def register(self, name): def
decorator(cls): self._plugins[name] = cls; return cls return decorator def run(self, name, *args):
if name in self._plugins: return self._plugins[name](*args).execute() print(f"Plugin '{name}' not
found.") pm = PluginManager() @[Link]("csv_exporter") class CSVExporter: def __init__(self,
data): [Link] = data def execute(self): print(f"Exporting {len([Link])} rows to CSV...")
@[Link]("json_exporter") class JSONExporter: def __init__(self, data): [Link] = data def
execute(self): print(f"Exporting {len([Link])} rows to JSON...") data = [1,2,3,4,5]
[Link]("csv_exporter", data) [Link]("json_exporter", data) [Link]("xml_exporter", data) # not
registered
#92 — Notification System
Send different notification types using OOP.
class Notification: def __init__(self, recipient, message): [Link] = recipient;
[Link] = message def send(self): raise NotImplementedError class
EmailNotification(Notification): def send(self): print(f"Email to {[Link]}:
{[Link]}") class SMSNotification(Notification): def send(self): print(f"SMS to
{[Link]}: {[Link][:50]}...") class PushNotification(Notification): def send(self):
print(f"Push → {[Link]}: {[Link]}") class NotificationService: def __init__(self):
[Link] = [] def add(self, notif): [Link](notif) def send_all(self): for n in
[Link]: [Link]() [Link]() svc = NotificationService()
[Link](EmailNotification("elemson@[Link]","CBU enrollment open!"))
[Link](SMSNotification("0977123456","Your application was received."))
[Link](PushNotification("elemson_app","New Python tutorial available!")) svc.send_all()
#93 — File System Simulator
Simulate a directory tree using OOP and dicts.
class File: def __init__(self, name, content=""): [Link] = name; [Link] = content def
size(self): return len([Link]) def __repr__(self): return f"File({[Link]},
{[Link]()}b)" class Directory: def __init__(self, name): [Link] = name; [Link] = {}
def add(self, item): [Link][[Link]] = item def get(self, name): return
[Link](name) def ls(self, indent=0): print(" "*indent + f"/{[Link]}") for child in
[Link](): if isinstance(child, Directory): [Link](indent+2) else: print("
"*(indent+2) + str(child)) root = Directory("root") docs = Directory("documents")
[Link](File("[Link]","My CV content here")) [Link](File("[Link]","Python OOP notes..."))
[Link](docs) [Link](File("[Link]","Welcome!")) [Link]()
#94 — OOP Calculator
A calculator with history using OOP.
class Calculator: def __init__(self): [Link] = [] def _op(self, a, b, op): ops =
{"+":a+b,"-":a-b,"*":a*b,"/":a/b if b else "ERR"} result = [Link](op, "Unknown op")
[Link]({"expr":f"{a}{op}{b}","result":result}) return result def add(self,a,b):
return self._op(a,b,"+") def sub(self,a,b): return self._op(a,b,"-") def mul(self,a,b): return
self._op(a,b,"*") def div(self,a,b): return self._op(a,b,"/") def show_history(self): for i,h in
enumerate([Link],1): print(f" {i}. {h['expr']} = {h['result']}") c = Calculator()
print([Link](10,5)); print([Link](3,7)); print([Link](20,4)) c.show_history()
#95 — Event Calendar
An event calendar using OOP and dicts.
from datetime import date class Event: def __init__(self, title, event_date, location="TBD"):
[Link] = title; [Link] = event_date; [Link] = location def __repr__(self): return
f"{[Link]} | {[Link]} @ {[Link]}" class Calendar: def __init__(self): [Link] =
{} # date -> list of events def add(self, event): [Link]([Link],
[]).append(event) def on(self, d): return [Link](d, []) def upcoming(self): today =
[Link]() future = {d:e for d,e in [Link]() if d >= today} for d in sorted(future):
[print(f" {e}") for e in future[d]] cal = Calendar() [Link](Event("CBU Orientation",
date(2026,11,1), "Kitwe")) [Link](Event("Python Workshop", date(2026,11,15),"Lusaka"))
[Link](Event("Forex Seminar", date(2026,12,5), "Online")) print("Upcoming events:")
[Link]()
#96 — Smart Home
Model a smart home system with OOP.
class Device: def __init__(self, name, room): [Link] = name; [Link] = room; [Link] = False
def toggle(self): [Link] = not [Link] def status(self): return "ON" if [Link] else "OFF" def
__repr__(self): return f"{[Link]}[{[Link]()}]" class SmartHome: def __init__(self):
[Link] = {} def add(self, device): [Link][[Link]] = device def control(self,
name, state): d = [Link](name) if d: [Link] = state; print(f"{name} turned {'on' if state
else 'off'}.") def room_status(self, room): devs = [d for d in [Link]() if [Link] ==
room] print(f"{room}: {devs}") def all_off(self): for d in [Link](): [Link] = False
print("All devices off.") home = SmartHome() [Link](Device("Living Light","Living Room"))
[Link](Device("AC","Bedroom")) [Link](Device("TV","Living Room")) [Link]("TV", True)
[Link]("AC", True) home.room_status("Living Room") home.all_off()
#97 — Quiz Engine
Build a quiz engine with scoring.
class Question: def __init__(self, text, options, answer): [Link] = text; [Link] =
options; [Link] = answer def check(self, attempt): return [Link]().upper() ==
[Link]() class Quiz: def __init__(self, title): [Link] = title; [Link] = []
def add(self, q): [Link](q) def run_demo(self, demo_answers): score = 0 for i, (q,
ans) in enumerate(zip([Link], demo_answers),1): correct = [Link](ans) if correct: score
+= 1 print(f"Q{i}: {'✓' if correct else '✗'} (your: {ans}, correct: {[Link]})") print(f"Score:
{score}/{len([Link])}") quiz = Quiz("Python Basics") [Link](Question("What does OOP
stand for?", ["A: Object Oriented Programming","B: Only One Problem"], "A"))
[Link](Question("Which keyword defines a class?", ["A: def","B: class"], "B"))
[Link](Question("What is a list in Python?", ["A: Ordered mutable sequence","B: Immutable
pair"], "A")) quiz.run_demo(["A","B","A"])
#98 — Social Media Feed
Model a social media post and feed system.
class Post: post_count = 0 def __init__(self, author, content): Post.post_count += 1 [Link] =
Post.post_count [Link] = author; [Link] = content [Link] = 0; [Link] = []
def like(self): [Link] += 1 def comment(self, user, text):
[Link]({"user":user,"text":text}) def __repr__(self): return f"[{[Link]}]
@{[Link]}: {[Link][:40]}... ❤ {[Link]}" class Feed: def __init__(self): [Link]
= [] def post(self, author, content): p=Post(author,content); [Link](p); return p def
trending(self): return sorted([Link],key=lambda p:-[Link])[:3] feed = Feed() p1 =
[Link]("Elemson","Just enrolled at CBU for Mechatronics Engineering!") p2 =
[Link]("Mwila","Studying for CSCA exam...") p3 = [Link]("Elemson","Python OOP finally makes
sense after 100 programs!") [Link](); [Link](); [Link](); [Link](); [Link]()
[Link]("Mwila","Congrats!") print("Trending:", [Link]())
#99 — Mini ORM
Simulate a basic Object-Relational Mapper.
class Field: def __init__(self, field_type, required=True): self.field_type = field_type;
[Link] = required class ModelMeta(type): def __new__(mcs, name, bases, attrs): fields =
{k:v for k,v in [Link]() if isinstance(v,Field)} attrs["_fields"] = fields return
super().__new__(mcs, name, bases, attrs) class Model(metaclass=ModelMeta): _db = [] def
__init__(self, **kwargs): for k,v in [Link](): setattr(self, k, v) def save(self):
self.__class__._db.append(self) @classmethod def all(cls): return cls._db @classmethod def
filter(cls, **kwargs): return [r for r in cls._db if all(getattr(r,k,None)==v for k,v in
[Link]())] def __repr__(self): return str({f:getattr(self,f,None) for f in self._fields})
class Student(Model): name = Field(str) course = Field(str) gpa = Field(float)
Student(name="Elemson",course="Mechatronics",gpa=4.0).save() Student(name="Mwila",
course="Medicine", gpa=3.5).save() Student(name="Chanda", course="Mechatronics",gpa=3.8).save()
print([Link](course="Mechatronics"))
Tip: This is how Django's ORM works under the hood — metaclasses magic!
#100 — The Grand Finale — Mini Python Academy
Combine everything: classes, lists, dicts, OOP patterns.
class Lesson: def __init__(self, title, topic): [Link] = title; [Link] = topic;
[Link] = False def complete(self): [Link] = True def __repr__(self): return f"{'✓'
if [Link] else '■'} {[Link]}" class Student: def __init__(self, name): [Link] =
name; [Link] = []; [Link] = [] def enroll(self, lesson): [Link](lesson)
def study(self, title): for l in [Link]: if [Link] == title: [Link](); return def
progress(self): done = sum(1 for l in [Link] if [Link]) pct =
done/len([Link])*100 if [Link] else 0 print(f"{[Link]}: {done}/{len([Link])}
lessons ({pct:.0f}%)") def award(self, badge): [Link](badge); print(f"Badge unlocked:
{badge}!") class Academy: def __init__(self): [Link] = {}; [Link] = {} def
add_lesson(self, title, topic): [Link][title] = Lesson(title, topic) def register(self,
name): s = Student(name) for l in [Link](): [Link](Lesson([Link], [Link]))
[Link][name] = s; return s def leaderboard(self): ranked = sorted([Link](),
key=lambda s: sum(1 for l in [Link] if [Link]), reverse=True) print("=== LEADERBOARD ===")
for i,s in enumerate(ranked,1): print(f" #{i} ",end=""); [Link]() academy = Academy() for
title,topic in [ ("Lists 101","Lists"),("Dicts 101","Dicts"), ("OOP Basics","OOP"),("OOP
Advanced","OOP"),("Projects","Combined") ]: academy.add_lesson(title, topic) e =
[Link]("Elemson") m = [Link]("Mwila") for lesson in ["Lists 101","Dicts
101","OOP Basics","OOP Advanced","Projects"]: [Link](lesson) for lesson in ["Lists 101","Dicts
101","OOP Basics"]: [Link](lesson) [Link]("Python Master ■") [Link]()
Tip: You just finished 100 Python programs. You are no longer a beginner.