Assignment Overview
In this assignment, you will build a complete Inventory Management System for a retail store. This comprehensive project requires you to apply ALL concepts from Module 2: variables, data types, operators, control flow, functions, lists, tuples, dictionaries, sets, comprehensions, and file handling (text, CSV, and JSON formats).
csv, json).
No pandas, numpy, or any third-party libraries allowed. This tests your understanding of pure Python.
Core Python (2.1)
Variables, operators, if/elif/else, for/while loops, functions
Data Structures (2.2)
Lists, tuples, dictionaries, sets, and comprehensions
File Handling (2.3)
Text files, CSV (csv module), JSON (json module), context managers
The Scenario
TechMart Electronics Store
You have been hired as a Python Developer at TechMart Electronics, a retail store that needs an inventory management system. The store manager has given you this task:
"We have product data in CSV format and supplier info in JSON format. We need a Python system that can track inventory, calculate profits, identify low-stock items, find unique categories, process sales transactions, and generate daily reports. Can you build this for us?"
Your Task
Create a Jupyter Notebook called inventory_system.ipynb that implements a complete
inventory management system. Your code must read from both CSV and JSON files, process data
using all data structures taught in Module 2, and write output to multiple file formats.
The Datasets
You will work with TWO data files. Create these files exactly as shown below:
File 1: products.csv (Product Inventory)
product_id,name,category,cost_price,sell_price,stock,reorder_level
P001,Laptop Pro 15,Electronics,45000,62000,25,10
P002,Wireless Mouse,Accessories,800,1200,150,50
P003,USB-C Hub,Accessories,1500,2200,80,30
P004,Mechanical Keyboard,Accessories,3500,4800,45,20
P005,27" Monitor,Electronics,18000,24000,30,15
P006,Webcam HD,Electronics,2500,3500,60,25
P007,Laptop Stand,Accessories,1200,1800,90,40
P008,External SSD 1TB,Storage,6000,8500,35,15
P009,Wireless Earbuds,Electronics,4000,5500,55,20
P010,Power Bank 20000mAh,Electronics,1800,2800,100,35
P011,HDMI Cable 2m,Accessories,300,500,200,75
P012,Tablet Pro,Electronics,35000,45000,20,8
P013,Smart Watch,Electronics,12000,16000,40,15
P014,Portable Speaker,Electronics,2200,3200,65,25
P015,Mouse Pad XL,Accessories,400,650,180,60
File 2: suppliers.json (Supplier Information)
{
"suppliers": [
{"id": "SUP01", "name": "TechWorld Inc", "categories": ["Electronics"], "rating": 4.5, "lead_days": 7},
{"id": "SUP02", "name": "AccessoryHub", "categories": ["Accessories"], "rating": 4.2, "lead_days": 3},
{"id": "SUP03", "name": "StoragePlus", "categories": ["Storage"], "rating": 4.8, "lead_days": 5},
{"id": "SUP04", "name": "GadgetZone", "categories": ["Electronics", "Accessories"], "rating": 3.9, "lead_days": 10}
],
"last_updated": "2024-12-01"
}
CSV Columns Explained
product_id- Unique identifier (string)name- Product name (string)category- Product category (string)cost_price- Purchase price in rupees (integer)sell_price- Selling price in rupees (integer)stock- Current quantity in stock (integer)reorder_level- Minimum stock before reordering (integer)
Requirements
Your inventory_system.ipynb must implement ALL of the following functions.
Each function is mandatory and will be tested individually.
Load Products from CSV
Create a function load_products(filename) that:
- Uses Python's
csvmodule with context manager (withstatement) - Returns a list of dictionaries, each representing a product
- Converts numeric fields (cost_price, sell_price, stock, reorder_level) to integers
def load_products(filename):
"""Load product data from CSV file using csv module."""
# Must use: with open(), csv.DictReader()
# Return: list of dicts with proper type conversion
pass
Load Suppliers from JSON
Create a function load_suppliers(filename) that:
- Uses Python's
jsonmodule with context manager - Returns the suppliers list from the JSON data
def load_suppliers(filename):
"""Load supplier data from JSON file."""
# Must use: with open(), json.load()
pass
Calculate Profit Margins
Create a function calculate_profit(product) that:
- Takes a product dictionary as input
- Returns a tuple:
(profit_per_unit, profit_margin_percent, total_potential_profit) - Profit margin = ((sell_price - cost_price) / cost_price) * 100
- Total potential profit = profit_per_unit × stock
def calculate_profit(product):
"""Return tuple: (profit_per_unit, margin_percent, total_profit)"""
# Must return a TUPLE (not list, not dict)
pass
Get Unique Categories (Using Set)
Create a function get_unique_categories(products) that:
- Uses a set to find all unique product categories
- Must use set comprehension
- Returns a sorted list of unique categories
def get_unique_categories(products):
"""Return sorted list of unique categories using set comprehension."""
# Must use: set comprehension {... for ... in ...}
pass
Find Low Stock Items
Create a function get_low_stock_items(products) that:
- Finds products where
stock <= reorder_level - Must use list comprehension with condition
- Returns list of tuples:
(product_id, name, stock, reorder_level)
def get_low_stock_items(products):
"""Return low stock items using list comprehension."""
# Must use: list comprehension with if condition
pass
Group Products by Category (Dictionary)
Create a function group_by_category(products) that:
- Creates a dictionary with category names as keys
- Values are lists of product dictionaries in that category
- Must use loops and dictionary operations
def group_by_category(products):
"""Return dict with category as key, list of products as value."""
# Example: {"Electronics": [product1, product2, ...], ...}
pass
Get Top Profitable Products
Create a function get_top_products(products, n=5) that:
- Sorts products by total potential profit (descending)
- Uses
sorted()with a lambda function as key - Returns top N products as list of tuples:
(name, total_profit)
def get_top_products(products, n=5):
"""Return top N products by profit using sorted() with lambda."""
# Must use: sorted(products, key=lambda ...)
pass
Find Suppliers for Category
Create a function find_suppliers_for_category(suppliers, category) that:
- Finds all suppliers that serve the given category
- Category must be in supplier's "categories" list
- Returns list of supplier names, sorted by rating (highest first)
Process Sale Transaction
Create a function process_sale(products, product_id, quantity) that:
- Finds the product by ID in the products list
- Checks if sufficient stock is available
- If yes: reduces stock, returns tuple
(True, total_sale_amount, profit) - If no: returns tuple
(False, 0, 0) - Uses
if/elif/elsecontrol flow properly
Generate Inventory Report (Text File)
Create a function generate_text_report(products, suppliers, filename) that:
- Uses context manager (
with) to write to a text file - Includes: header with date, inventory summary, low stock alerts, category breakdown, top products
- Uses proper string formatting
Export Updated Inventory to CSV
Create a function save_products_csv(products, filename) that:
- Uses
csv.DictWriterto write products back to CSV - Preserves the same column order as the original file
- Uses context manager for file handling
Main Program
Create a main() function that:
- Loads products from CSV and suppliers from JSON
- Prints inventory statistics to console
- Simulates 3 sale transactions (you choose product_ids and quantities)
- Generates the text report
- Saves updated inventory to a new CSV file
- Uses the
if __name__ == "__main__":pattern
def main():
# Load data
products = load_products("products.csv")
suppliers = load_suppliers("suppliers.json")
# Display stats
print(f"Loaded {len(products)} products")
print(f"Categories: {get_unique_categories(products)}")
# Process sales
process_sale(products, "P001", 2)
process_sale(products, "P005", 1)
process_sale(products, "P010", 5)
# Generate outputs
generate_text_report(products, suppliers, "inventory_report.txt")
save_products_csv(products, "updated_inventory.csv")
print("Inventory system complete!")
if __name__ == "__main__":
main()
Submission
Create a public GitHub repository with the exact name shown below:
Required Repository Name
techmart-inventory-system
Required Files
techmart-inventory-system/
├── inventory_system.ipynb # Your Jupyter Notebook with ALL 12 functions
├── products.csv # Input dataset (as provided or modified)
├── suppliers.json # Input dataset (as provided or modified)
├── inventory_report.txt # Generated text report from running your notebook
├── updated_inventory.csv # Updated CSV after processing sales
└── README.md # REQUIRED - see contents below
README.md Must Include:
- Your full name and submission date
- Brief description of your solution approach
- Any challenges faced and how you solved them
- Instructions to run your notebook
Do Include
- All 12 functions implemented and working
- Docstrings for every function
- Comments explaining complex logic
- Both output files from running your notebook
- Use of comprehensions where specified
- README.md with all required sections
Do Not Include
- External libraries (ONLY csv and json allowed)
- Any .pyc or __pycache__ files (use .gitignore)
- Virtual environment folders
- Code that doesn't run without errors
- Hardcoded outputs (we will test with different data)
Enter your GitHub username - we'll verify your repository automatically
Grading Rubric
Your assignment will be graded on the following criteria:
| Criteria | Points | Description |
|---|---|---|
| File Handling (CSV & JSON) | 30 | Correct use of csv and json modules with context managers for all file operations |
| Functions (12 required) | 50 | All 12 functions implemented correctly with proper logic and return types |
| Data Structures | 40 | Correct use of lists, tuples (for returns), dictionaries (for grouping), and sets (for unique values) |
| Comprehensions | 25 | Proper use of list comprehensions and set comprehensions where specified |
| Control Flow | 20 | Correct use of if/elif/else, for loops, and while loops |
| Code Quality | 35 | Docstrings, comments, naming conventions, and clean organization |
| Total | 200 |
Ready to Submit?
Make sure you have completed all requirements and reviewed the grading rubric above.
Submit Your AssignmentWhat You Will Practice
Functions & Lambda (2.1)
Writing 12 modular functions with parameters, return values, docstrings, and using lambda for sorting
All Data Structures (2.2)
Lists for collections, tuples for fixed returns, dictionaries for grouping, sets for unique values, comprehensions for transformation
CSV & JSON File Handling (2.3)
Reading CSV with csv.DictReader, writing with csv.DictWriter, loading JSON with json.load, all using context managers
Real-World Data Processing
Calculating profit margins, sorting products, grouping by category, processing transactions, and generating reports
Pro Tips
Python Best Practices
- Use meaningful variable and function names
- Break complex problems into smaller functions
- Handle edge cases (empty lists, missing keys)
- Test functions with different inputs
File Handling
- Always use
withstatement for files - Validate data after loading from files
- Handle file not found errors gracefully
- Use proper encoding (UTF-8) for text files
Time Management
- Start with data loading functions
- Build and test functions incrementally
- Don't over-engineer - keep it simple
- Leave time for testing and documentation
Common Mistakes
- Modifying lists while iterating over them
- Not handling JSON parsing errors
- Forgetting to convert types (str to int)
- Using mutable default arguments