1. Introduction to Portfolio Capstone Projects
Congratulations on reaching Lesson 20! You have successfully mastered the complete core foundations of Python programming—ranging from syntax, indentation, data types, and arithmetic operators to advanced control flow (if-elif-else), structural pattern matching (match-case), definite and indefinite loops (for, while), functions, scope, functional tools, and modular package management.
Learning syntax rules in isolation is only half the journey. True software engineering competence comes from Architectural Synthesis: combining distinct language features into a cohesive, robust, production-ready application.
In this Capstone Project lesson, we will step through architecting and building an enterprise-grade Command-Line Interface (CLI) Quiz Application. This project will serve as a permanent portfolio piece that demonstrates your ability to write clean, modular, and maintainable Python code.
2. System Architecture & Requirements Specification
1. Core Features Checklist
- Interactive Terminal Interface: Driven by an indefinite
while Truemenu loop with clear navigation options. - Modular Data Model: Storing quiz question banks, multiple-choice options, correct option keys, and difficulty categories cleanly.
- Command & Action Dispatcher: Utilizing
match-casepattern matching to route user commands, validate options, and dispatch quiz operations. - Scoring & Grade Evaluation: Calculating point totals, accuracy percentages, and performance grades using mathematical functions and conditionals.
- Input Sanitization & Guard Clauses: Cleaning user responses using string methods (
.strip(),.upper()) and guarding against invalid entries. - Functional Analytics & High Scores: Utilizing functional tools (
filter(),map(),sorted()with lambdas) to process question statistics and leaderboard rankings.
2. High-Level Flowchart Diagram
+-----------------------------------------------------------------------+
| System Initialization |
| (Load Constants, Question Bank, & System Global State) |
+-----------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------+
| Main CLI Loop (while True) |
| Display Navigation Banner & Capture Command Tokens |
+-----------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------+
| Match-Case Pattern Matching Dispatcher |
| ["START", mode] | ["STATS"] | ["ADD", ...] | ["EXIT" | "QUIT"] |
+-------------------+-------------+----------------+--------------------+
| | | |
v v v v
Execute Quiz Calculate & Append New Terminate
Engine Loop Display Stats Question Data Session Safely
3. Data Structure Design for Quiz Data
Before writing application logic, we must design a clean, flexible data structure to represent questions. A list of dynamic dictionaries or structured tuples allows effortless iteration and pattern matching.
# Standard Question Data Structure Template
QUESTION_BANK = [
{
"id": 101,
"category": "PYTHON_BASICS",
"question": "Which keyword is used to define an anonymous inline function?",
"options": ["A) def", "B) lambda", "C) func", "D) anon"],
"correct": "B",
"points": 10
},
{
"id": 102,
"category": "CONTROL_FLOW",
"question": "Which Python version officially introduced structural 'match-case'?",
"options": ["A) Python 3.8", "B) Python 3.9", "C) Python 3.10", "D) Python 3.12"],
"correct": "C",
"points": 10
},
{
"id": 103,
"category": "FUNCTIONS",
"question": "What is the return data type of the built-in input() function?",
"options": ["A) int", "B) float", "C) str", "D) bool"],
"correct": "C",
"points": 10
}
]
print(f"Question Bank Loaded: {len(QUESTION_BANK)} total items.")
Question Bank Loaded: 3 total items.
4. Step-by-Step Implementation of the Quiz Engine
1. Core Evaluation Helper Functions
We build modular, pure functions responsible for grading, formatting score cards, and displaying individual questions.
def evaluate_performance(score: int, total_possible: int) -> tuple[str, float]:
"""
Calculates accuracy percentage and assigns performance tier grade.
Uses conditional if-elif-else logic and returns tuple.
"""
if total_possible == 0:
return "N/A", 0.0
accuracy_pct = (score / total_possible)
if accuracy_pct >= 0.90:
grade = "EXCELLENT (Mastery Tier)"
elif accuracy_pct >= 0.70:
grade = "GOOD (Proficient Tier)"
elif accuracy_pct >= 0.50:
grade = "SATISFACTORY (Apprentice Tier)"
else:
grade = "NEEDS_IMPROVEMENT (Novice Tier)"
return grade, accuracy_pct
def format_score_card(user_name: str, score: int, total_possible: int) -> str:
"""Formats a visual score card using f-strings and padding alignment."""
grade, pct = evaluate_performance(score, total_possible)
banner = "=" * 45
card = (
f"\n{banner}\n"
f" OFFICIAL QUIZ SCORECARD\n"
f"{banner}\n"
f"Candidate Name : {user_name.title()}\n"
f"Raw Points Earned: {score} / {total_possible}\n"
f"Accuracy Rate : {pct:.1%}\n"
f"Performance Tier : {grade}\n"
f"{banner}\n"
)
return card
# Testing helper functions standalone
print(format_score_card("alice dev", 20, 30))
=============================================
OFFICIAL QUIZ SCORECARD
=============================================
Candidate Name : Alice Dev
Raw Points Earned: 20 / 30
Accuracy Rate : 66.7%
Performance Tier : SATISFACTORY (Apprentice Tier)
=============================================
2. Integrating Structural Pattern Matching in the Interactive Loop
The core engine uses a while True menu loop that tokenizes user input and uses match-case to trigger actions cleanly.
def run_quiz_session(questions: list, user_name: str) -> int:
"""Executes definite iteration for the active quiz attempt."""
score = 0
print(f"\n--- Starting Quiz Session for {user_name.title()} ---")
for idx, q in enumerate(questions, start=1):
print(f"\nQuestion #{idx}: {q['question']}")
for opt in q["options"]:
print(f" {opt}")
# Simulating automated response choice for demonstration
# In a real app, response = input("Select (A/B/C/D): ").strip().upper()
simulated_answers = ["B", "C", "C"] # B (correct), C (correct), C (correct)
user_choice = simulated_answers[idx - 1]
print(f"Selected Answer: {user_choice}")
# Validation using conditional pattern guard
if user_choice == q["correct"]:
print(f"SUCCESS: Correct! (+{q['points']} pts)")
score += q["points"]
else:
print(f"WRONG: Correct answer was {q['correct']}.")
return score
# Dispatcher function utilizing match-case pattern matching
def process_cli_command(command_line: str, question_bank: list, session_state: dict):
tokens = command_line.strip().split()
match tokens:
case ["START", user_name]:
total_possible = sum(q["points"] for q in question_bank)
earned_points = run_quiz_session(question_bank, user_name)
# Record audit session state
session_state["history"].append((user_name, earned_points, total_possible))
print(format_score_card(user_name, earned_points, total_possible))
case ["START"]:
print("ERROR: Please specify a user name! Usage: START ")
case ["FILTER", "CATEGORY", cat_name]:
cat_clean = cat_name.upper().strip()
filtered = list(filter(lambda q: q["category"] == cat_clean, question_bank))
print(f"\nCategory '{cat_clean}' Questions Found ({len(filtered)}):")
for q in filtered:
print(f" -> [{q['id']}] {q['question']}")
case ["STATS"]:
print("\n=== SYSTEM PERFORMANCE STATS ===")
if not session_state["history"]:
print("No quiz sessions completed yet.")
else:
for name, pts, total in session_state["history"]:
grade, pct = evaluate_performance(pts, total)
print(f"User: {name:<12} | Score: {pts:>2}/{total:<2} | Accuracy: {pct:.1%}")
case ["EXIT" | "QUIT"]:
print("\n[SYSTEM] Terminating Quiz Engine. Session closed safely.")
return "TERMINATE"
case _:
print(f"ERROR: Command '{command_line}' unrecognized. Type START , FILTER CATEGORY , STATS, or EXIT.")
return "CONTINUE"
# Testing dispatcher execution
state = {"history": []}
process_cli_command("START Candidate_One", QUESTION_BANK, state)
process_cli_command("STATS", QUESTION_BANK, state)
--- Starting Quiz Session for Candidate_One ---
Question #1: Which keyword is used to define an anonymous inline function?
A) def
B) lambda
C) func
D) anon
Selected Answer: B
SUCCESS: Correct! (+10 pts)
Question #2: Which Python version officially introduced structural 'match-case'?
A) Python 3.8
B) Python 3.9
C) Python 3.10
D) Python 3.12
Selected Answer: C
SUCCESS: Correct! (+10 pts)
Question #3: What is the return data type of the built-in input() function?
A) int
B) float
C) str
D) bool
Selected Answer: C
SUCCESS: Correct! (+10 pts)
=============================================
OFFICIAL QUIZ SCORECARD
=============================================
Candidate Name : Candidate_One
Raw Points Earned: 30 / 30
Accuracy Rate : 100.0%
Performance Tier : EXCELLENT (Mastery Tier)
=============================================
=== SYSTEM PERFORMANCE STATS ===
User: Candidate_One | Score: 30/30 | Accuracy: 100.0%
5. Complete Master Source Code (`master_quiz_system.py`)
Below is the complete, single-file modular CLI application combining all components into a production-ready script.
"""
Master Command-Line Quiz System
Author: Python Mastery Course
Description: End-to-end Capstone Project consolidating Lessons 1-20.
"""
import sys
from datetime import datetime
# ==========================================
# 1. CONSTANTS & SYSTEM STATE
# ==========================================
APP_TITLE = "ENTERPRISE PYTHON CLI QUIZ OS"
VERSION = "2.0.0"
QUESTION_REPOSITORY = [
{
"id": 1,
"category": "SYNTAX",
"question": "Which character introduces a single-line comment in Python?",
"options": ["A) //", "B) /*", "C) #", "D)
OnlineCBT