Assignment 2-A

Python Practice Problems

Build a complete inventory management system that combines all Module 2 concepts: variables, control flow, functions, lists, dictionaries, tuples, sets, comprehensions, and file handling with CSV and JSON formats.

6-8 hours
Challenging
200 Points
Submit Assignment
What You'll Practice
  • Use all Python data types correctly
  • Apply lists, dicts, tuples, and sets
  • Write functions with proper structure
  • Use list/dict comprehensions
  • Handle CSV and JSON files
Contents
01

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

No External Libraries: You must use ONLY Python's built-in modules (csv, json). No pandas, numpy, or any third-party libraries allowed. This tests your understanding of pure Python.
Skills Applied: This assignment tests your understanding of Python basics (Topic 2.1), data structures (Topic 2.2), and file handling (Topic 2.3) from Module 2.
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

Ready to submit? Already completed the assignment? Submit your work now!
Submit Now
02

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.

03

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

Requirements

Your inventory_system.ipynb must implement ALL of the following functions. Each function is mandatory and will be tested individually.

1
Load Products from CSV

Create a function load_products(filename) that:

  • Uses Python's csv module with context manager (with statement)
  • 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
2
Load Suppliers from JSON

Create a function load_suppliers(filename) that:

  • Uses Python's json module 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
3
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
4
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
5
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
6
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
7
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
8
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)
9
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/else control flow properly
10
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
11
Export Updated Inventory to CSV

Create a function save_products_csv(products, filename) that:

  • Uses csv.DictWriter to write products back to CSV
  • Preserves the same column order as the original file
  • Uses context manager for file handling
12
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()
05

Submission

Create a public GitHub repository with the exact name shown below:

Required Repository Name
techmart-inventory-system
github.com/<your-username>/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)
Important: Before submitting, run all cells in your notebook to make sure it executes without errors and generates both output files correctly!
Submit Your Assignment

Enter your GitHub username - we'll verify your repository automatically

06

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 Assignment
07

What 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

08

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 with statement 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
09

Pre-Submission Checklist

Code Requirements
Repository Requirements