Hello! Welcome to my blog.
None of us is unfamiliar with the calculator in Math lessons. Today, by reading my blog, you'll create that calculator, but entirely by code! With only a few lines of Python code, you're going to make a calculator by yourself! You don't have to be a professional programmer, nor do you have to know complex algorithms - only need a computer and a little bit of curiosity. Don't waste time anymore, let's get into it!
Resource: Mart Production from Pexels
1. Prepare:- Download Python: https://www.python.org/downloads/
When you download Python, it also has the code compiler (IDLE).
- Or: Visual Studio Code: https://code.visualstudio.com/download
IDLE of Python.
2. Write the programBelow is the code for the Python simple calculator. I'll leave the code, and in the next topic, I'm going to explain the code.
My code (Edited through Carbon)
You can view the full source code on my GitHub here:
3. Explain the code- Program Introduction:
The code:
This line simply prints the title of the program, so the user knows what the script does.
- Infinite Loop:
The code:
We use an infinite loop so that the calculator can keep running until the users decide to exit.
- Getting User Input:
The code:
The input() function asks the users for data from the keyboard (as a string).The float() function changes that string into a floating-point number so we can do calculations with decimals.
- Choosing An Operation:
The code:
The program asks the user to choose what operation they want: addition, subtraction, multiplication, or division.
- Performing The Calculation:
The code:
We use if..., elif..., else..., statements to check which operation the user chose.
If division is selected, we add a check to make sure num2 is not zero (to avoid errors).
If the user types an invalid symbol, the program prints an error message.
- Ask The User To Continue Or Not:
The code:
The program asks if the user wants to calculate again.
.lower() makes the input lowercase, so it works even if the user types "YES" or "Yes".
If the answer is not "yes" (or "YES", "Yes",...), the "break" commands the while loop to stop and stop the program.
Output:
Here's the output of this program ( this is the example):
And that's it, you've created a simple calculator using Python! This project is a fun and beginner-friendly way to practice your coding skills. You've learned how to take user input, perform basic calculations, and display the results. Projects like this help you understand the fundamentals of Python and give you confidence to try more complex programs in the future.
Now, fire up your Python editor and give it a try. Happy coding! 🚀
Connect with me:
Email: trinhlehoangphuoc@gmail.com
See you next Friday!
It’s a little bit trick for me.
ReplyDelete