Electricity bill with slabs
Write a Python program to calculate an electricity bill: first 50 units Rs 0.50, next 100 units Rs 0.75, next 100 units Rs 1.25, above 250 units Rs 1.50, plus a 17% surcharge.
350
438.75 90.67
Approach
- Walk through the slabs with a loop, charging the units that fall in each one.
Solution
slabs = [(50, 0.50), (100, 0.75), (100, 1.25), (float("inf"), 1.50)] def bill(units): amount = 0 for size, rate in slabs: used = min(units, size) amount += used * rate units -= used if units == 0: break return round(amount * 1.17, 2) print(bill(350))print(bill(120))438.75 90.67
Line by line
Each slab is (number of units, price per unit); the last slab has no limit.
Take as many units as fit in the slab, charge them and subtract them.
Add the 17% surcharge.
Learn the concept
New to this topic? Read the lesson, then come back.