Python Practice › Loop Programs › Program 50

Electricity bill with slabs

MediumLoop Programs · 50 of 90

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.

Advertisement
Input
350
Output
438.75
90.67

Approach

  1. Walk through the slabs with a loop, charging the units that fall in each one.

Solution

Python
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))
Output
438.75
90.67

Line by line

Line 1

Each slab is (number of units, price per unit); the last slab has no limit.

Lines 6-8

Take as many units as fit in the slab, charge them and subtract them.

Line 11

Add the 17% surcharge.

Advertisement

Learn the concept

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

More loop programs

← All 90 Loop Programs