Editor

Python Program to Calculate Profit or Loss

Beginner · Basics

When something is sold for more than it cost there is a profit, and when it is sold for less there is a loss. The cost price (CP) is what you paid and the selling price (SP) is what you sold it for, and this program works out the profit or loss and its percentage.

Program

profit_or_loss.py
cost_price = 1200 # or: cost_price = float(input("Enter the cost price: "))
selling_price = 1500 # or: selling_price = float(input("Enter the selling price: "))
if selling_price > cost_price:
profit = selling_price - cost_price
percent = profit / cost_price * 100
print(f"Profit: Rs {profit}")
print(f"Profit percentage: {percent:.2f}%")
elif cost_price > selling_price:
loss = cost_price - selling_price
percent = loss / cost_price * 100
print(f"Loss: Rs {loss}")
print(f"Loss percentage: {percent:.2f}%")
else:
print("No profit, no loss")
Output
Profit: Rs 300
Profit percentage: 25.00%

How it works

  1. If the selling price is higher than the cost price, the difference selling_price - cost_price is the profit.
  2. If the cost price is higher, the difference the other way round is the loss.
  3. Profit and loss percentages are always worked out on the cost price: profit / cost_price * 100.
  4. When the two prices are equal, the else branch reports no profit and no loss.

Another way to write it

Using a function for many sales

Using a function for many sales
def profit_or_loss(cp, sp):
diff = sp - cp
if diff > 0:
return f"profit of Rs {diff} ({diff / cp * 100:.1f}%)"
elif diff < 0:
return f"loss of Rs {-diff} ({-diff / cp * 100:.1f}%)"
return "no profit, no loss"
sales = [(1200, 1500), (800, 650), (500, 500)]
for cp, sp in sales:
print(f"CP {cp}, SP {sp}: {profit_or_loss(cp, sp)}")
Output
CP 1200, SP 1500: profit of Rs 300 (25.0%)
CP 800, SP 650: loss of Rs 150 (18.8%)
CP 500, SP 500: no profit, no loss

A single difference tells the whole story: positive means profit, negative means loss, and -diff turns a loss into a positive amount for printing.

Try it yourself

Change the program to find the selling price needed for a 20% profit on the same cost price.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises