write a program to calculate electricity bill in python
Introduction
In our increasingly digitized world, the ability to automate mundane tasks through programming has become an invaluable skill. One such practical application is calculating electricity bills using Python. In this blog post, we’ll explore how to create a simple yet effective program to calculate electricity bills. Whether you’re a programming novice or a seasoned developer, this guide will break down the problem, present a basic solution, and then delve into more advanced aspects like error handling and using functions.
The Whole Program
Before we dive into the intricacies of the code, let’s take a look at the complete program:
# Electricity Bill Calculator in Python
def calculate_bill(units):
"""
Calculate electricity bill based on the number of units consumed.
"""
if units <= 50:
bill = units * 2.5
elif 50 < units <= 100:
bill = 50 * 2.5 + (units - 50) * 3.0
elif 100 < units <= 200:
bill = 50 * 2.5 + 50 * 3.0 + (units - 100) * 5.0
else:
bill = 50 * 2.5 + 50 * 3.0 + 100 * 5.0 + (units - 200) * 7.5
return bill
# Input
units_consumed = float(input("Enter the number of units consumed: "))
# Calculate and display the bill
total_bill = calculate_bill(units_consumed)
print(f"Your electricity bill is: ${total_bill:.2f}")
Breaking Down the Problem
Understanding the Logic
The electricity bill is often calculated based on the number of units consumed. Different slabs have different rates. For instance:
- Up to 50 units: $2.5 per unit
- 51 to 100 units: $3.0 per unit
- 101 to 200 units: $5.0 per unit
- Above 200 units: $7.5 per unit
We can use these conditions to determine the appropriate rate for each slab and calculate the total bill.
Example Scenario:
Suppose a household consumes 120 units of electricity in a billing cycle.
Calculate the Bill:
- For the first 50 units: 50 units×$2.5/unit50 units×$2.5/unit
- For the next 50 units (51 to 100): (120 units−50 units)×$3.0/unit(120 units−50 units)×$3.0/unit
- For the remaining units (101 to 120): 20 units×$5.0/unit20 units×$5.0/unit
Sum Up the Bills:
- Total Bill = (50×2.5)+(50×3.0)+(20×5.0)(50×2.5)+(50×3.0)+(20×5.0)
Calculation:
Let’s compute the total bill using the identified slabs and rates:
Total Bill=(50×2.5)+(50×3.0)+(20×5.0)Total Bill=(50×2.5)+(50×3.0)+(20×5.0)
Total Bill=125+150+100Total Bill=125+150+100
Total Bill=$375Total Bill=$375
Taking User Input
The program begins by taking user input for the number of units consumed. The float() function ensures that the input is treated as a floating-point number, allowing for decimal values.
Breaking Down the Code - Step by Step
Step 1: Defining the Function
The core logic is encapsulated in the calculate_bill function. This function takes the number of units as a parameter and calculates the bill based on the predefined slabs.
Step 2: Applying Conditions
The if-elif-else statements in the function determine which slab the given number of units falls into and calculate the corresponding bill.
Step 3: Returning the Result
The calculated bill is returned by the function.
Step 4: Taking User Input and Displaying Result
The user is prompted to enter the units consumed. The program then calls the calculate_bill function with the user input and displays the result.
Advanced Code with Error Handling
To enhance the robustness of our program, let’s add error handling for invalid inputs. We’ll use a try-except block to catch potential errors, such as non-numeric inputs.
# Advanced Electricity Bill Calculator with Error Handling
def calculate_bill(units):
"""
Calculate electricity bill based on the number of units consumed.
"""
if units <= 0:
raise ValueError("Units consumed must be greater than zero.")
if units <= 50:
bill = units * 2.5
elif 50 < units <= 100:
bill = 50 * 2.5 + (units - 50) * 3.0
elif 100 < units <= 200:
bill = 50 * 2.5 + 50 * 3.0 + (units - 100) * 5.0
else:
bill = 50 * 2.5 + 50 * 3.0 + 100 * 5.0 + (units - 200) * 7.5
return bill
# Input with error handling
try:
units_consumed = float(input("Enter the number of units consumed: "))
if units_consumed < 0:
raise ValueError("Units consumed cannot be negative.")
except ValueError as e:
print(f"Error: {e}")
else:
# Calculate and display the bill
total_bill = calculate_bill(units_consumed)
print(f"Your electricity bill is: ${total_bill:.2f}")
Certainly, let’s break down the code for error handling in the electricity bill calculator. The primary goal of error handling is to ensure that the program gracefully handles unexpected situations, such as invalid user inputs. In the given example, we use a try-except block to catch potential errors and provide meaningful error messages to the user.
Now, let’s break down the error handling part step by step:
Step 1: User Input with try-except
try:
units_consumed = float(input("Enter the number of units consumed: "))
if units_consumed < 0:
raise ValueError("Units consumed cannot be negative.")
except ValueError as e:
print(f"Error: {e}")
- The
tryblock attempts to execute the code inside it. - The
float(input(...))statement takes user input and attempts to convert it to a floating-point number. - If the user enters a non-numeric value, a
ValueErroris raised, and the control moves to theexceptblock. - Within the
exceptblock, we catch theValueErrorand print an error message indicating that there was an issue with the input.
Step 2: Handling Negative Values
if units_consumed < 0:
raise ValueError("Units consumed cannot be negative.")
- After successfully converting the user input to a float, we check if it’s a negative value.
- If it’s negative, we raise another
ValueErrorwith a specific error message.
Step 3: Calculation and Display
else:
# Calculate and display the bill
total_bill = calculate_bill(units_consumed)
print(f"Your electricity bill is: ${total_bill:.2f}")
- If there are no errors in the user input, the
elseblock is executed. - The program proceeds to calculate the electricity bill using the
calculate_billfunction and displays the result.
This error handling mechanism ensures that the program informs the user about the nature of any input-related issues and prevents the program from crashing due to unexpected inputs.
Using Functions for Modularity
In programming, it’s good practice to modularize code. Let’s refactor our program by breaking it into smaller functions for better readability and maintainability.
# Modular Electricity Bill Calculator
def calculate_bill(units):
"""
Calculate electricity bill based on the number of units consumed.
"""
if units <= 0:
raise ValueError("Units consumed must be greater than zero.")
if units <= 50:
return units * 2.5
elif 50 < units <= 100:
return 50 * 2.5 + (units - 50) * 3.0
elif 100 < units <= 200:
return 50 * 2.5 + 50 * 3.0 + (units - 100) * 5.0
else:
return 50 * 2.5 + 50 * 3.0 + 100 * 5.0 + (units - 200) * 7.5
def get_user_input():
"""
Get user input for the number of units consumed.
"""
try:
units = float(input("Enter the number of units consumed: "))
if units < 0:
raise ValueError("Units consumed cannot be negative.")
return units
except ValueError as e:
print(f"Error: {e}")
return None
def main():
"""
Main function to run the program.
"""
units_consumed = get_user_input()
if units_consumed is not None:
total_bill = calculate_bill(units_consumed)
print(f"Your electricity bill is: ${total_bill:.2f}")
if __name__ == "__main__":
main()
Conclusion
In this comprehensive guide, we’ve walked through the process of creating a Python program to calculate electricity bills. Starting with a basic solution, we then explored advanced concepts like error handling and modularization using functions. Whether you’re a beginner or an experienced programmer, this guide provides a solid foundation for tackling real-world problems with Python. Feel free to experiment and enhance the program further to suit your specific needs. Happy coding