Electricity bill with slabs
Write a Python program to calculate an electricity bill. Units 1-50 cost Rs 0.50, units 51-100 Rs 0.75, units 101-250 Rs 1.25 and units above 250 Rs 1.50 each. Add a 17% surcharge.
350 units
40 units -> 23.4 120 units -> 102.38 350 units -> 468.0
Approach
- Charge each slab only for the units that fall in it.
- Add 17% to the total.
Solution
def bill(units): amount = 0 if units > 250: amount += (units - 250) * 1.50 units = 250 if units > 100: amount += (units - 100) * 1.25 units = 100 if units > 50: amount += (units - 50) * 0.75 units = 50 amount += units * 0.50 return round(amount * 1.17, 2) for u in [40, 120, 350]: print(u, "units ->", bill(u))40 units -> 23.4 120 units -> 102.38 350 units -> 468.0
Line by line
Units above 250 are charged at 1.50, then units is capped at 250 for the next slab.
Each lower slab takes the units between its limits.
The first 50 units (or fewer) cost 0.50 each.
Multiplying by 1.17 adds the 17% surcharge.
The original sample output (438.75 for 350 units) did not follow these slabs. With slab pricing, 350 units cost 25 + 37.5 + 187.5 + 150 = 400, plus 17% = 468.0.
Learn the concept
New to this topic? Read the lesson, then come back.