Complete Python Series · Part 29 of 29
Project: Course Enrollment & Checkout System
NextGen CTO — Course Enrollment & Checkout System
Project description
Build an interactive command-line application for the NextGen CTO learning platform. Students and college coordinators can browse a course catalog, discover courses within a budget, select course licenses, apply a promotional discount and generate a final enrollment receipt.
You will combine Python data structures, flow control, functions, string formatting and functional programming into one working application. Each task builds upon the previous one in a single main.py file.
Level: Beginner to intermediate | Language: Python 3 | Dependencies: Standard library only
This is an educational simulation: prices, license counts and promotional rules are sample data. Checkout does not collect payments or enroll real users. Floating-point arithmetic is used for learning; production billing should use decimal or integer minor-unit arithmetic.
Learning objectives
- Model structured data with dictionaries and tuples, and manage mutable session state.
- Parse and validate command-line input using string operations and control flow.
- Use comprehensions, lambda expressions,
filter()andfunctools.reduce(). - Pass functions as arguments and compose reusable helpers.
- Format currency, generate receipts and integrate an interactive command loop.
Commands
Course keys are single tokens (for example, SystemDesign) so plain .split() can parse commands without a more advanced parser. All prices are in INR.
Task roadmap
- Task 0: Initialize the Learning Platform
- Task 1: Build the Course Catalog
- Task 2: Manage the Enrollment Cart
- Task 3: Process Course Selection Commands
- Task 4: Discover Courses Within a Budget
- Task 5: Generate Enrollment Receipt Lines
- Task 6: Build the Billing Calculator
- Task 7: Implement Dynamic Pricing and Checkout
- Task 8: Build the Interactive Command Console
- Complete solution
- Example session
- Verification checklist
Task 0: Initialize the Learning Platform
Set up the single-file project and import the standard-library module needed for aggregation.
All code belongs in main.py (or main.py in your local project folder). No external packages are required.
Task requirements
- Create
main.py - Import
functools - Leave space for the catalog, cart, helper functions and command console.
Use the concepts covered so far. Add this task to the same main.py file, keeping earlier implementations.
Good luck trying the task!
Starter code
# TODO: Import functools
# TODO: Add the catalog, cart and functions in subsequent tasks
Hints
The functools module is part of Python; import it once at the top.
import functools
Solution explanation: import functools makes the module available to later functions. Keep imports at the top and append each completed task below the preceding task.
Quick check: Run python main.py. Nothing is printed yet; this is expected.
Task 1: Build the Course Catalog
Represent the available courses and their metadata using a dictionary of tuples.
The catalog is the authoritative source of course prices and categories. Treat it as read-only throughout the application (uppercase naming is a convention, not enforced immutability).
Task requirements
- Define
COURSE_CATALOGin global scope - Include six courses
- Use a single-token course name as each key and a
(float, str)tuple as each value. Use the sample catalog below so later examples match.
Use the concepts covered so far. Add this task to the same main.py file, keeping earlier implementations.
Good luck trying the task!
Starter code
# TODO: Define COURSE_CATALOG with six courses
# Each entry: "CourseName": (price, category)
Hints
Use uppercase for constants. A tuple can hold a price and category; index 0 retrieves the price.
COURSE_CATALOG = {
"Python": (999.0, "Programming"),
"DSA": (1499.0, "Interview Prep"),
"SystemDesign": (2499.0, "Architecture"),
"DBMS": (799.0, "Fundamentals"),
"Networking": (899.0, "Fundamentals"),
"AIEngineering": (2999.0, "Artificial Intelligence")
}
Solution explanation: The dictionary maps names to tuples. The tuple groups the price and category without requiring a custom class. The catalog remains unchanged during checkout.
Quick check: COURSE_CATALOG["Python"][0] evaluates to 999.0.
Task 2: Manage the Enrollment Cart
Maintain mutable session state in a global dictionary.
A learner or college coordinator can select several licenses for each course before checkout.
Task requirements
- Create an empty global dictionary named
enrollment_cart - Use canonical course names as keys and integer license counts as values. Do not modify the catalog when updating the cart.
Use the concepts covered so far. Add this task to the same main.py file, keeping earlier implementations.
Good luck trying the task!
Starter code
# TODO: Initialize the enrollment cart
Hints
An empty dictionary is written as {}. Define it outside functions so all helpers can access the same object.
enrollment_cart = {}
Solution explanation: The cart and catalog have different responsibilities: the catalog stores metadata and the cart stores quantities. Mutating the global dictionary does not require the global keyword because the function does not rebind its name.
Quick check: Initially, enrollment_cart is {}.
Task 3: Process Course Selection Commands
Practice token parsing, validation, case-insensitive matching and dictionary updates.
The command console will pass a list such as ["add", "python", "2"] to the selection processor.
Task requirements
- Create
add_course(parts: list) - Reject commands with fewer than two tokens
- Find the canonical catalog key case-insensitively
- Reject unknown courses without modifying the cart
- Default missing or invalid quantities to 1 (including zero and negative quantities)
- Increment existing entries using the canonical key
- Print a confirmation.
Use the concepts covered so far. Add this task to the same main.py file, keeping earlier implementations.
Good luck trying the task!
Starter code
def add_course(parts: list):
# TODO: Validate the number of tokens
# TODO: Find the matching course name
# TODO: Parse quantity, defaulting to 1
# TODO: Update enrollment_cart and confirm
pass
Hints
Check the length before indexing. Use .lower() for comparison; isascii() and isdigit() together accept ASCII digits only; check that the quantity is positive. Use the matched catalog key for both lookup and update.
def add_course(parts: list):
"""Add course licenses using a tokenized command."""
if len(parts) < 2:
print("Usage: add <course> [quantity]")
return
requested_name = parts[1]
course_name = None
for name in COURSE_CATALOG:
if name.lower() == requested_name.lower():
course_name = name
break
if course_name is None:
print(f"Course not found: {requested_name}")
return
quantity = 1
if len(parts) > 2:
token = parts[2]
if token.isascii() and token.isdigit() and len(token) <= 9:
parsed_quantity = int(token)
if parsed_quantity > 0:
quantity = parsed_quantity
if course_name in enrollment_cart:
enrollment_cart[course_name] += quantity
else:
enrollment_cart[course_name] = quantity
print(f"Added {quantity} license(s) for {course_name}.")
Solution explanation: The early returns prevent invalid requests from changing state. The loop captures the canonical key, so mixed-case additions update the same entry. Quantity validation avoids invalid integer conversion and keeps quantities positive.
Quick check: From an empty cart, call add_course(["add", "python", "2"]) and then add_course(["add", "PYTHON"]). The cart becomes {"Python": 3}. The quantity parser accepts up to nine ASCII digits to avoid excessively large integer inputs; other quantities default to 1.
Task 4: Discover Courses Within a Budget
Use functional filtering with a lambda expression.
Learners should be able to discover courses whose individual license price fits their budget.
Task requirements
- Define
find_courses_within_budget(max_price: float) - Use
filter()and a lambda to retain catalog keys with price less than or equal to the budget - Convert the iterator to a list
- Print matching names or a helpful no-results message.
Use the concepts covered so far. Add this task to the same main.py file, keeping earlier implementations.
Good luck trying the task!
Starter code
def find_courses_within_budget(max_price: float):
# TODO: Filter catalog keys with filter() and lambda
# TODO: Print matching courses or a no-results message
pass
Hints
Iterating over a dictionary yields keys. Use COURSE_CATALOG[name][0] to retrieve the price. Wrap filter() in list() and use join() for readable output.
def find_courses_within_budget(max_price: float):
"""Display courses priced at or below the supplied budget."""
matches = list(filter(
lambda name: COURSE_CATALOG[name][0] <= max_price,
COURSE_CATALOG
))
if matches:
print(f"Courses within INR {max_price:.2f}: {', '.join(matches)}")
else:
print(f"No courses within INR {max_price:.2f}.")
Solution explanation: The lambda runs for every catalog key. filter() yields matching keys lazily; converting to a list lets us test whether matches exist and join them into one readable string. The comparison includes the boundary price.
Quick check: find_courses_within_budget(999.0) prints Courses within INR 999.00: Python, DBMS, Networking.
Task 5: Generate Enrollment Receipt Lines
Transform cart entries into formatted strings with a list comprehension.
Each receipt line must show the number of licenses, course name and combined cost.
Task requirements
- Define
generate_receipt_lines() -> list - Iterate over
enrollment_cart.items()in a list comprehension - Multiply the unit price by quantity
- Format the amount to two decimal places
- Return the list instead of printing it.
Use the concepts covered so far. Add this task to the same main.py file, keeping earlier implementations.
Good luck trying the task!
Starter code
def generate_receipt_lines() -> list:
# TODO: Return a list comprehension of formatted receipt lines
pass
Hints
Unpack each pair as name, quantity. Use :<15 to align the course name and :.2f for currency.
def generate_receipt_lines() -> list:
"""Return formatted receipt lines for the selected courses."""
return [
f"{quantity} x {name:<15} = INR {COURSE_CATALOG[name][0] * quantity:.2f}"
for name, quantity in enrollment_cart.items()
]
Solution explanation: .items() produces key-value pairs. The comprehension transforms each pair into a formatted string; the multiplication computes the line cost. Returning data lets checkout decide how to display it.
Quick check: With enrollment_cart = {"Python": 2}, the returned list contains "2 x Python = INR 1998.00". An empty cart returns [].
Task 6: Build the Billing Calculator
Aggregate line-item amounts using functools.reduce().
The checkout needs the subtotal before any promotions are applied.
Task requirements
- Define
calculate_subtotal() -> float - Build a list of line costs using a comprehension
- Use
functools.reduce()with a lambda and an initial value of0.0 - Return the total. Do not use an explicit loop or
sum()for this task.
Use the concepts covered so far. Add this task to the same main.py file, keeping earlier implementations.
Good luck trying the task!
Starter code
def calculate_subtotal() -> float:
# TODO: Build a list of individual course costs
# TODO: Aggregate the costs using functools.reduce()
pass
Hints
The accumulator starts at 0.0. This also handles empty lists without a separate conditional.
def calculate_subtotal() -> float:
"""Return the total cost before promotional discounts."""
line_costs = [
COURSE_CATALOG[name][0] * quantity
for name, quantity in enrollment_cart.items()
]
return functools.reduce(lambda total, cost: total + cost, line_costs, 0.0)
Solution explanation: The comprehension creates individual costs. The reducer combines each cost with the running accumulator; 0.0 ensures a floating-point result even when the cart is empty.
Quick check: With two Python licenses and one SystemDesign license, the subtotal is 4497.0. An empty cart returns 0.0.
Task 7: Implement Dynamic Pricing and Checkout
Compose helper functions and pass a pricing strategy as a function argument.
NextGen CTO offers a sample bulk purchase promotion: 10% off when the subtotal is strictly greater than INR 5000.
Task requirements
- Create
apply_pricing_strategy(total: float, strategy_func) -> floatreturning the result of calling the strategy - Create
checkout() - Return early for an empty cart
- Print receipt lines
- Calculate subtotal
- Pass a conditional lambda to the pricing helper
- Display subtotal, discount and grand total to two decimal places
- Clear the cart after checkout.
Use the concepts covered so far. Add this task to the same main.py file, keeping earlier implementations.
Good luck trying the task!
Starter code
def apply_pricing_strategy(total: float, strategy_func) -> float:
# TODO: Call and return the supplied strategy
pass
def checkout():
# TODO: Handle an empty cart
# TODO: Print receipt lines and calculate subtotal
# TODO: Apply the promotional strategy
# TODO: Display totals and clear the cart
pass
Hints
Use lambda amount: amount * 0.90 if amount > 5000 else amount. Join receipt lines with "\n".join(...). The discount is the difference between subtotal and final amount.
def apply_pricing_strategy(total: float, strategy_func) -> float:
"""Apply a caller-provided pricing strategy."""
return strategy_func(total)
def checkout():
"""Generate a receipt, apply the promotion and reset the cart."""
if not enrollment_cart:
print("Enrollment cart is empty.")
return
print("\n--- NEXTGEN CTO ENROLLMENT RECEIPT ---")
print("\n".join(generate_receipt_lines()))
subtotal = calculate_subtotal()
grand_total = apply_pricing_strategy(
subtotal, lambda amount: amount * 0.90 if amount > 5000 else amount
)
print("-" * 45)
print(f"Subtotal: INR {subtotal:.2f}")
print(f"Discount: INR {subtotal - grand_total:.2f}")
print(f"Grand Total: INR {grand_total:.2f}")
enrollment_cart.clear()
Solution explanation: The pricing helper accepts behavior as an argument, rather than hard-coding a promotion. Checkout orchestrates earlier helpers, computes the discount, and clears the existing cart object only after printing the receipt.
Quick check: Three SystemDesign licenses cost INR 7497.00 before discount, INR 749.70 discount, and INR 6747.30 after discount. Exactly INR 5000 receives no discount.
Task 8: Build the Interactive Command Console
Integrate all helpers into a persistent command-line application.
The console is the entry point through which students browse, select and purchase licenses.
Task requirements
- Define
start_app() - Print a welcome message
- Read commands in a
while Trueloop - Strip and split input
- Skip empty input
- Normalize the command to lowercase
- Route
show,add,search,checkoutandquit - Validate non-negative decimal search prices before conversion
- Print a helpful message for unknown commands
- Invoke the function at the end of the script.
Use the concepts covered so far. Add this task to the same main.py file, keeping earlier implementations.
Good luck trying the task!
Starter code
def start_app():
# TODO: Print available commands
# TODO: Build the interactive loop
# TODO: Route commands and validate search input
# TODO: Break on quit
pass
# TODO: Start the application
Hints
Use .split() without an argument to handle repeated spaces. For a budget token, remove at most one decimal point before checking digits. The checkout branch only needs to call checkout() because it already coordinates earlier helpers.
def start_app():
"""Run the interactive enrollment console."""
print("Welcome to NextGen CTO Course Enrollment!")
print("Commands: show, add <course> [quantity], search <budget>, checkout, quit")
while True:
parts = input("\n> ").strip().split()
if not parts:
continue
command = parts[0].lower()
if command == "quit":
print("Thank you for visiting NextGen CTO!")
break
elif command == "show":
print("\n--- COURSE CATALOG ---")
for name, (price, category) in COURSE_CATALOG.items():
print(f"{name:<15} INR {price:>8.2f} | {category}")
elif command == "add":
add_course(parts)
elif command == "search":
if len(parts) == 2:
budget = parts[1]
digits = budget.replace(".", "", 1)
if digits.isascii() and digits.isdigit() and len(digits) <= 15:
find_courses_within_budget(float(budget))
continue
print("Usage: search <non-negative budget>")
elif command == "checkout":
checkout()
else:
print("Unknown command. Try show, add, search, checkout or quit.")
start_app()
Solution explanation: The loop keeps the application running until break. Empty input is skipped before indexing. The command dispatch separates input handling from business logic. The final start_app() call starts the interactive session.
Quick check: Try show, search 1000, add python 2, checkout, then quit. The console accepts non-negative decimal budgets with up to 15 digits; malformed or excessively long values display usage guidance.
Complete solution
After completing all tasks, your main.py should look like this. Run it with python main.py.
# Task 0: Initialize the Learning Platform
import functools
# Task 1: Build the Course Catalog
COURSE_CATALOG = {
"Python": (999.0, "Programming"),
"DSA": (1499.0, "Interview Prep"),
"SystemDesign": (2499.0, "Architecture"),
"DBMS": (799.0, "Fundamentals"),
"Networking": (899.0, "Fundamentals"),
"AIEngineering": (2999.0, "Artificial Intelligence")
}
# Task 2: Manage the Enrollment Cart
enrollment_cart = {}
# Task 3: Process Course Selection Commands
def add_course(parts: list):
"""Add course licenses using a tokenized command."""
if len(parts) < 2:
print("Usage: add <course> [quantity]")
return
requested_name = parts[1]
course_name = None
for name in COURSE_CATALOG:
if name.lower() == requested_name.lower():
course_name = name
break
if course_name is None:
print(f"Course not found: {requested_name}")
return
quantity = 1
if len(parts) > 2:
token = parts[2]
if token.isascii() and token.isdigit() and len(token) <= 9:
parsed_quantity = int(token)
if parsed_quantity > 0:
quantity = parsed_quantity
if course_name in enrollment_cart:
enrollment_cart[course_name] += quantity
else:
enrollment_cart[course_name] = quantity
print(f"Added {quantity} license(s) for {course_name}.")
# Task 4: Discover Courses Within a Budget
def find_courses_within_budget(max_price: float):
"""Display courses priced at or below the supplied budget."""
matches = list(filter(
lambda name: COURSE_CATALOG[name][0] <= max_price,
COURSE_CATALOG
))
if matches:
print(f"Courses within INR {max_price:.2f}: {', '.join(matches)}")
else:
print(f"No courses within INR {max_price:.2f}.")
# Task 5: Generate Enrollment Receipt Lines
def generate_receipt_lines() -> list:
"""Return formatted receipt lines for the selected courses."""
return [
f"{quantity} x {name:<15} = INR {COURSE_CATALOG[name][0] * quantity:.2f}"
for name, quantity in enrollment_cart.items()
]
# Task 6: Build the Billing Calculator
def calculate_subtotal() -> float:
"""Return the total cost before promotional discounts."""
line_costs = [
COURSE_CATALOG[name][0] * quantity
for name, quantity in enrollment_cart.items()
]
return functools.reduce(lambda total, cost: total + cost, line_costs, 0.0)
# Task 7: Implement Dynamic Pricing and Checkout
def apply_pricing_strategy(total: float, strategy_func) -> float:
"""Apply a caller-provided pricing strategy."""
return strategy_func(total)
def checkout():
"""Generate a receipt, apply the promotion and reset the cart."""
if not enrollment_cart:
print("Enrollment cart is empty.")
return
print("\n--- NEXTGEN CTO ENROLLMENT RECEIPT ---")
print("\n".join(generate_receipt_lines()))
subtotal = calculate_subtotal()
grand_total = apply_pricing_strategy(
subtotal, lambda amount: amount * 0.90 if amount > 5000 else amount
)
print("-" * 45)
print(f"Subtotal: INR {subtotal:.2f}")
print(f"Discount: INR {subtotal - grand_total:.2f}")
print(f"Grand Total: INR {grand_total:.2f}")
enrollment_cart.clear()
# Task 8: Build the Interactive Command Console
def start_app():
"""Run the interactive enrollment console."""
print("Welcome to NextGen CTO Course Enrollment!")
print("Commands: show, add <course> [quantity], search <budget>, checkout, quit")
while True:
parts = input("\n> ").strip().split()
if not parts:
continue
command = parts[0].lower()
if command == "quit":
print("Thank you for visiting NextGen CTO!")
break
elif command == "show":
print("\n--- COURSE CATALOG ---")
for name, (price, category) in COURSE_CATALOG.items():
print(f"{name:<15} INR {price:>8.2f} | {category}")
elif command == "add":
add_course(parts)
elif command == "search":
if len(parts) == 2:
budget = parts[1]
digits = budget.replace(".", "", 1)
if digits.isascii() and digits.isdigit() and len(digits) <= 15:
find_courses_within_budget(float(budget))
continue
print("Usage: search <non-negative budget>")
elif command == "checkout":
checkout()
else:
print("Unknown command. Try show, add, search, checkout or quit.")
start_app()
Example session
Welcome to NextGen CTO Course Enrollment!
Commands: show, add <course> [quantity], search <budget>, checkout, quit
> search 1000
Courses within INR 1000.00: Python, DBMS, Networking
> add python 2
Added 2 license(s) for Python.
> add SystemDesign 2
Added 2 license(s) for SystemDesign.
> checkout
--- NEXTGEN CTO ENROLLMENT RECEIPT ---
2 x Python = INR 1998.00
2 x SystemDesign = INR 4998.00
---------------------------------------------
Subtotal: INR 6996.00
Discount: INR 699.60
Grand Total: INR 6296.40
> checkout
Enrollment cart is empty.
> quit
Thank you for visiting NextGen CTO!
Verification checklist
Project completion
You have built a complete command-line enrollment and checkout simulator using only the Python fundamentals covered in the course. As an optional extension, add a remove command or a category-based search without changing the existing billing helpers.