BinaryTree
Intermediate
Python Course
BinaryTree Digital Education Program
Week 5
Small Project &
Putting Everything Together
Final Project
Time to put our
skills to the test.
This week we build a real project combining everything we've learned.
What Will This Project Incorporate?
File Handling
Reading and writing data using JSON and CSV files.
Data Visualization
Analyzing and displaying data using Matplotlib.
OOP Principles
Organizing code using classes, objects, and methods.
Dictionaries
Using dictionaries as the core data structure for storing items.
The Project: Console Item Lister
Build a console-based item lister that saves data to a JSON file and displays a Matplotlib histogram.
1
Console Input
User types keywords like 'create' or 'makelist'. Program reads input and branches based on the command.
2
Save to JSON
Each item (with name, price, and quantity) gets saved to a JSON file — persistent across runs.
3
Histogram
When triggered, generate a Matplotlib histogram of total prices (item price × quantity).
Timeline
When is this due?
1
Final project presentations take place next week as the last assignment of the program.
2
Ensure your project is complete, functional, and ready to present.
3
Apply OOP principles to organize your code cleanly.
Structuring a Python Project
Large projects can seem overwhelming. These strategies make them manageable:
Break It Into Steps
Decompose the project into small, achievable tasks. Build and test one piece at a time.
Visualize First
Sketch your classes, their attributes, methods, and how they connect — on paper or a tool.
Debug Methodically
Use print statements to trace execution. Test each method independently before combining.
Tips: Writing Reusable Functions
For Matplotlib and other tools, write functions that rely only on their arguments — not global variables.
def show_histogram(items):� """Display a histogram of total prices (price × quantity)."""� names = [item["name"] for item in items]� totals = [item["price"] * item["qty"] for item in items]�� plt.bar(names, totals, color="teal")� plt.title("Total Price by Item")� plt.ylabel("Total ($)")� plt.show()�
The Console
command = input("Enter a command: ")�if command == "create":� name = input("Item name: ")� price = float(input("Price: "))�
Walkthrough
Example Project
Code Review
The following slides walk through a complete implementation. Follow along and take notes.
Example Project — Part 1: Imports & Setup
import json�import matplotlib.pyplot as plt��FILENAME = "items.json"��def load_items():� try:� with open(FILENAME) as f:� return json.load(f)� except FileNotFoundError:� return []�
Example Project — Part 2: Saving Items
def save_items(items):� with open(FILENAME, "w") as f:� json.dump(items, f, indent=2)��def create_item(name, price, qty):� return {"name": name, "price": price, "qty": qty}�
Example Project — Part 3: Histogram
def show_histogram(items):� if not items:� print("No items to display.")� return�� names = [i["name"] for i in items]� totals = [i["price"] * i["qty"] for i in items]�� plt.bar(names, totals, color="teal")� plt.title("Total Price per Item")� plt.ylabel("Total ($)")� plt.show()�
Example Project — Part 4: Main Loop
items = load_items()��while True:� cmd = input("Command (create / list / chart / quit): ").strip()�� if cmd == "create":� name = input(" Name: ")� price = float(input(" Price: $"))� qty = int(input(" Quantity: "))� items.append(create_item(name, price, qty))� save_items(items)� print(" Item saved!\n")�
Example Project — Part 5: List & Chart Commands
elif cmd == "list":� for item in items:� print(f' {item["name"]} — ${item["price"]} x {item["qty"]}')� print()�� elif cmd == "chart":� show_histogram(items)�� elif cmd == "quit":� print("Goodbye!")� break�� else:� print("Unknown command.")�
Example Project — Part 6: OOP Refactor (Bonus)
class Item:� def __init__(self, name, price, qty):� self.name = name� self.price = price� self.qty = qty�� def total(self):� return self.price * self.qty�� def to_dict(self):� return {"name": self.name, "price": self.price, "qty": self.qty}�
Code Reviews — A Professional Practice
Code reviews are when teammates read each other's code and provide structured feedback.
Ensures Conventions
Check that team members follow coding standards and style guides.
Clean Output
Catch messy logic, redundant code, or structural issues before they ship.
Fewer Bugs
A fresh set of eyes often spots errors the original author missed.
How to Debug — Reading Tracebacks
When an error occurs, Python prints a traceback — a trail of code execution leading to the error.
Traceback (most recent call last):� File "main.py", line 10, in <module> ← entry point� File "main.py", line 1, in foo ← through a function� File "main.py", line 6, in fer ← where error originates�TypeError: unsupported operand type(s) for **: 'str' and 'int'
Read bottom-up
Read bottom-up: The last line tells you what went wrong. Work upward to see how you got there.
Isolate the method
Isolate the method: Test individual functions with print statements to pinpoint where the error starts.
Week 5 Wrap-Up
The End!
Good luck on the project!
★
Build it step by step — no need to do it all at once.
★
Use print statements liberally when debugging.
★
Apply OOP principles — classes, methods, clean structure.