1 of 19

BinaryTree

Intermediate

Python Course

BinaryTree Digital Education Program

2 of 19

Week 5

Small Project &

Putting Everything Together

3 of 19

Final Project

Time to put our

skills to the test.

This week we build a real project combining everything we've learned.

4 of 19

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.

5 of 19

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).

6 of 19

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.

7 of 19

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.

8 of 19

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()�

9 of 19

The Console

  • Long before IDEs, the console was the primary coding interface — a black screen with line-by-line input.
  • Today, it's used to interact with system processes and run applications.
  • This project is console-based: Python reads keyword commands like 'create' or 'makelist'.
  • After a keyword, the program prompts for additional inputs, which are saved to a JSON file.

command = input("Enter a command: ")�if command == "create":� name = input("Item name: ")� price = float(input("Price: "))�

10 of 19

Walkthrough

Example Project

Code Review

The following slides walk through a complete implementation. Follow along and take notes.

11 of 19

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 []�

12 of 19

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}�

13 of 19

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()�

14 of 19

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")�

15 of 19

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.")�

16 of 19

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}�

17 of 19

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.

18 of 19

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.

19 of 19

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.