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 lessonWrite 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.
More Inventory System exercises
- Create the Database SchemaAdvanced
- Record TransactionsAdvanced
- Stock Level ReportAdvanced
- Low Stock Alert SystemAdvanced
- Transaction History ReportAdvanced
- The Complete InventorySystem ClassAdvanced
All Python exercises · 50 practice problems · Practical Projects quiz