Fruit shop management system

MediumFunction Programs · 30 of 39

Write a Python program with functions to add stock, sell fruit and show the inventory of a fruit shop.

Advertisement
Output
Sold 5 apple for Rs 600
Cannot sell 40 mango
apple    qty  45  Rs 120/kg
mango    qty  30  Rs 80/kg

Approach

  1. Keep the stock in a dictionary.
  2. Write one small function per action and a short script that uses them.

Solution

Python
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()
Output
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

Lines 3-6

setdefault creates the fruit on first use; later calls add to the quantity and update the price.

Lines 8-13

sell refuses unknown fruit or too large an order before changing anything.

Lines 15-17

show prints a neat inventory table.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs