Editor

Write the Add Product Function

Advanced · Write the code · from Build an Inventory Management System with SQLite

From the lesson: Step 2: Add Products to Inventory

With the schema in place, we need a function that inserts new products. A good function handles errors gracefully - what if someone tries to add a product that already exists? What if the price is negative?

Read this part of the lesson

Write a function add_product(cursor, name, category, price, quantity, reorder_level) that:

1. Inserts a new product into the products table.

2. Returns the new product's ID (use cursor.lastrowid).

3. If the product name already exists (IntegrityError), print "Product already exists: {name}" and return None.

After defining the function, create the schema, add 3 products (e.g., "Laptop" in "Electronics" at 999.99 with qty 50, "Mouse" in "Electronics" at 29.99 with qty 200, "Desk Chair" in "Furniture" at 249.99 with qty 30), and print each product's ID. Use reorder_level=10 for all.

import sqlite3
def add_product(cursor, name, category, price, quantity, reorder_level=10):
# Insert product and return its ID, handle duplicates
pass
# Create database and schema, then add products

More Inventory System exercises

All Python exercises · 50 practice problems · Practical Projects quiz