Python Program to Calculate an Electricity Bill
Beginner · Basics
Electricity is charged in slabs: the first block of units costs the least, and each further block costs more per unit. This program calculates a monthly bill from the units used, with sample slab rates; real rates differ from state to state and change from year to year.
Program
electricity_bill.py
units = 350 # or: units = int(input("Enter units consumed: "))
# Sample slab rates in Rs per unit (real tariffs differ by state and year):
# 1-100 units: 3.00, 101-200: 4.50, 201-300: 6.00, above 300: 7.50
if units <= 100:
energy = units * 3.00
elif units <= 200:
energy = 100 * 3.00 + (units - 100) * 4.50
elif units <= 300:
energy = 100 * 3.00 + 100 * 4.50 + (units - 200) * 6.00
else:
energy = 100 * 3.00 + 100 * 4.50 + 100 * 6.00 + (units - 300) * 7.50
fixed_charge = 50.00 # monthly meter charge, also a sample value
total = energy + fixed_charge
print("Units consumed:", units)
print(f"Energy charge: Rs {energy:.2f}")
print(f"Fixed charge: Rs {fixed_charge:.2f}")
print(f"Total bill: Rs {total:.2f}")
Output
Units consumed: 350 Energy charge: Rs 1725.00 Fixed charge: Rs 50.00 Total bill: Rs 1775.00
How it works
- The rates here are sample values for practice, so put in your own state's tariff to get a real bill.
- Each slab is charged only for the units that fall inside it: for 350 units, the first 100 cost Rs 3.00 each, the next 100 Rs 4.50, the next 100 Rs 6.00 and only the last 50 Rs 7.50.
- The
ifandelifchain picks the right formula for the number of units, adding up the full slabs below it. - A common mistake is to charge all 350 units at the top rate, which would give Rs 2625 instead of Rs 1725.
- The fixed charge is added at the end to give the total bill.
Another way to write it
Slabs stored in a list
Slabs stored in a list
units = 350
# (units in the slab, rate per unit); None means "all the rest"
slabs = [(100, 3.00), (100, 4.50), (100, 6.00), (None, 7.50)]
bill = 0
left = units
for size, rate in slabs:
used = left if size is None else min(left, size)
bill += used * rate
print(f"{used} units at Rs {rate:.2f} = Rs {used * rate:.2f}")
left -= used
if left == 0:
break
print(f"Energy charge for {units} units: Rs {bill:.2f}")
Output
100 units at Rs 3.00 = Rs 300.00 100 units at Rs 4.50 = Rs 450.00 100 units at Rs 6.00 = Rs 600.00 50 units at Rs 7.50 = Rs 375.00 Energy charge for 350 units: Rs 1725.00
With the slabs kept as data, a new tariff only changes the list, not the if chain, and the loop prints a breakdown like a real bill.
Try it yourself
Add a 5% surcharge on bills above Rs 2000 and print it as its own line.
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises