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:
*** QuickLaTeX cannot compile formula:
{total_bill:.2f}")
" style="color:#e1e4e8;display:none" aria-label="Copy" class="code-block-pro-copy-button"><svg xmlns="http://www.w3.org/2000/svg" style="width:24px;height:24px" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path class="with-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path><path class="without-check" stroke-linecap="round" stroke-linejoin="round" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path></svg></span><pre class="shiki github-dark" style="background-color: #24292e" tabindex="0"><code><span class="line"><span style="color: #E1E4E8"># Electricity Bill Calculator in Python</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8">def </span><span style="color: #B392F0">calculate_bill</span><span style="color: #E1E4E8">(units):</span></span>
<span class="line"><span style="color: #E1E4E8"> </span><span style="color: #9ECBFF">"""</span></span>
<span class="line"><span style="color: #9ECBFF"> Calculate electricity bill based on the number of units consumed.</span></span>
<span class="line"><span style="color: #9ECBFF"> """</span></span>
<span class="line"><span style="color: #E1E4E8"> </span><span style="color: #F97583">if</span><span style="color: #E1E4E8"> units </span><span style="color: #F97583"><=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">50</span><span style="color: #E1E4E8">:</span></span>
<span class="line"><span style="color: #E1E4E8"> bill </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> units </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">2.5</span></span>
<span class="line"><span style="color: #E1E4E8"> elif </span><span style="color: #79B8FF">50</span><span style="color: #E1E4E8"> </span><span style="color: #F97583"><</span><span style="color: #E1E4E8"> units </span><span style="color: #F97583"><=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">100</span><span style="color: #E1E4E8">:</span></span>
<span class="line"><span style="color: #E1E4E8"> bill </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">50</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">2.5</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> (units </span><span style="color: #F97583">-</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">50</span><span style="color: #E1E4E8">) </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">3.0</span></span>
<span class="line"><span style="color: #E1E4E8"> elif </span><span style="color: #79B8FF">100</span><span style="color: #E1E4E8"> </span><span style="color: #F97583"><</span><span style="color: #E1E4E8"> units </span><span style="color: #F97583"><=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">200</span><span style="color: #E1E4E8">:</span></span>
<span class="line"><span style="color: #E1E4E8"> bill </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">50</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">2.5</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">50</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">3.0</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> (units </span><span style="color: #F97583">-</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">100</span><span style="color: #E1E4E8">) </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">5.0</span></span>
<span class="line"><span style="color: #E1E4E8"> </span><span style="color: #F97583">else</span><span style="color: #E1E4E8">:</span></span>
<span class="line"><span style="color: #E1E4E8"> bill </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">50</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">2.5</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">50</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">3.0</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">100</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">5.0</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">+</span><span style="color: #E1E4E8"> (units </span><span style="color: #F97583">-</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">200</span><span style="color: #E1E4E8">) </span><span style="color: #F97583">*</span><span style="color: #E1E4E8"> </span><span style="color: #79B8FF">7.5</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8"> </span><span style="color: #F97583">return</span><span style="color: #E1E4E8"> bill</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8"># Input</span></span>
<span class="line"><span style="color: #E1E4E8">units_consumed </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #F97583">float</span><span style="color: #E1E4E8">(</span><span style="color: #B392F0">input</span><span style="color: #E1E4E8">(</span><span style="color: #9ECBFF">"Enter the number of units consumed: "</span><span style="color: #E1E4E8">))</span></span>
<span class="line"></span>
<span class="line"><span style="color: #E1E4E8"># Calculate and display the bill</span></span>
<span class="line"><span style="color: #E1E4E8">total_bill </span><span style="color: #F97583">=</span><span style="color: #E1E4E8"> </span><span style="color: #B392F0">calculate_bill</span><span style="color: #E1E4E8">(units_consumed)</span></span>
<span class="line"><span style="color: #B392F0">print</span><span style="color: #E1E4E8">(f</span><span style="color: #9ECBFF">"Your electricity bill is:
*** Error message:
You can't use `macro parameter character #' in math mode.
leading text: " style="color:#
You can't use `macro parameter character #' in math mode.
leading text: ...iki github-dark" style="background-color: #
You can't use `macro parameter character #' in math mode.
leading text: ...de><span class="line"><span style="color: #
You can't use `macro parameter character #' in math mode.
leading text: ...class="line"><span style="color: #E1E4E8">#
You can't use `macro parameter character #' in math mode.
leading text: <span class="line"><span style="color: #
You can't use `macro parameter character #' in math mode.
leading text: ... #E1E4E8">def </span><span style="color: #
You can't use `macro parameter character #' in math mode.
leading text: ...calculate_bill</span><span style="color: #
{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: 3.0 per unit
101 to 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/unit
For the next 50 units (51 to 100): (120 units−50 units)×3.0/unit
For the remaining units (101 to 120): 20 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=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.
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 try block 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 ValueError is raised, and the control moves to the except block.
Within the except block, we catch the ValueError and 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 ValueError with a specific error message.
Step 3: Calculation and Display
{total_bill:.2f}")
If there are no errors in the user input, the else block is executed.
The program proceeds to calculate the electricity bill using the calculate_bill function 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.
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