Python Program to Calculate Electricity Bill
bill = units * rate_per_unit.Examples
How to Think About It
Algorithm
Code
units = float(input('Enter units consumed: ')) rate_per_unit = 5.0 bill = units * rate_per_unit print('Electricity bill:', bill)
Dry Run
Let's trace the program with input 100 units.
Input units
User enters 100
Set rate
rate_per_unit = 5.0
Calculate bill
bill = 100 * 5.0 = 500.0
Print result
Print 'Electricity bill: 500.0'
| units | rate_per_unit | bill |
|---|---|---|
| 100 | 5.0 | 500.0 |
Why This Works
Step 1: Get input
We use input() to get the number of units consumed from the user as a string, then convert it to a float for calculation.
Step 2: Set rate
We define a fixed rate per unit, here 5.0, which means each unit costs 5 currency units.
Step 3: Calculate bill
We multiply the units by the rate using * operator to get the total bill.
Step 4: Display output
We print the result using print() so the user sees the total electricity bill.
Alternative Approaches
units = float(input('Enter units consumed: ')) if units <= 100: bill = units * 5 else: bill = 100 * 5 + (units - 100) * 7 print('Electricity bill:', bill)
def calculate_bill(units): rate = 5 return units * rate units = float(input('Enter units consumed: ')) bill = calculate_bill(units) print('Electricity bill:', bill)
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of operations regardless of input size, so it runs in constant time O(1).
Space Complexity
It uses a few variables and no extra data structures, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in constant time; using a function adds clarity but no significant speed difference.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple multiplication | O(1) | O(1) | Basic fixed rate calculation |
| Tiered rates | O(1) | O(1) | Realistic billing with slabs |
| Function encapsulation | O(1) | O(1) | Code reuse and clarity |