Fruit shop management system
Write a Python program with functions to add stock, sell fruit and show the inventory of a fruit shop.
Sold 5 apple for Rs 600 Cannot sell 40 mango apple qty 45 Rs 120/kg mango qty 30 Rs 80/kg
Approach
- Keep the stock in a dictionary.
- Write one small function per action and a short script that uses them.
Solution
stock = {} def add_fruit(name, qty, price): item = stock.setdefault(name, {"qty": 0, "price": price}) item["qty"] += qty item["price"] = price def sell(name, qty): item = stock.get(name) if not item or item["qty"] < qty: return f"Cannot sell {qty} {name}" item["qty"] -= qty return f"Sold {qty} {name} for Rs {qty * item['price']}" def show(): for name, item in stock.items(): print(f"{name:<8} qty {item['qty']:>3} Rs {item['price']}/kg") add_fruit("apple", 50, 120)add_fruit("mango", 30, 80)print(sell("apple", 5))print(sell("mango", 40))show()Sold 5 apple for Rs 600 Cannot sell 40 mango apple qty 45 Rs 120/kg mango qty 30 Rs 80/kg
Line by line
setdefault creates the fruit on first use; later calls add to the quantity and update the price.
sell refuses unknown fruit or too large an order before changing anything.
show prints a neat inventory table.
Learn the concept
New to this topic? Read the lesson, then come back.