Calculator in Python
Implementing a calculator in Python
Welcome to Day 2 of my 30-day Python coding challenge! Today, we will create a simple Python calculator. Like yesterday, the project is inspired by:
To add some fun, we’re integrating ASCII art into our calculator, drawing inspiration from ASCII Art Archive.
Calculator
The process of creating our calculator is straightforward:
"""Calculator."""
def display_calculator(input_str: str) -> None:
"""Display calculator.
:param input_str: Input to display on calculator.
"""
if len(input_str) > 15:
input_str = input_str[:12] + "..."
input_str = input_str[:15]
input_padding = 15 - len(input_str)
input_str = input_str + " " * input_padding
calculator = f"""
_____________________
| _________________ |
| | { input_str } | |
| |_________________| |
| ___ ___ ___ ___ |
| | 7 | 8 | 9 | | + | |
| |___|___|___| |___| |
| | 4 | 5 | 6 | | - | |
| |___|___|___| |___| |
| | 1 | 2 | 3 | | x | |
| |___|___|___| |___| |
| | . | 0 | = | | / | |
| |___|___|___| |___| |
|_____________________|
"""
print(calculator)
while True:
user_input = input("Enter an equation (or 'q' to quit): ")
if user_input == "q":
break
try:
evaluation = eval(user_input) # pylint: disable=eval-used
display_calculator(user_input + " = " + str(evaluation))
except Exception as e: # pylint: disable=broad-exception-caught
print("Error:", e)
This implementation performs basic calculations and brings them to life on a screen mimicking a classic calculator.
Running the program:
$ python easy/calculator.py
Enter an equation (or 'q' to quit): 1+2+3
_____________________
| _________________ |
| | 1+2+3 = 6 | |
| |_________________| |
| ___ ___ ___ ___ |
| | 7 | 8 | 9 | | + | |
| |___|___|___| |___| |
| | 4 | 5 | 6 | | - | |
| |___|___|___| |___| |
| | 1 | 2 | 3 | | x | |
| |___|___|___| |___| |
| | . | 0 | = | | / | |
| |___|___|___| |___| |
|_____________________|
What’s Next
Tomorrow, I’ll be completing the final challenge in our easy project series: creating a rock, paper, scissors game in Python. Stay tuned! All the code for these projects is available on Python Projects on GitHub.
Further Reading
If you want to learn more about programming and, specifically, Python and Java, see the following course:
Note: If you use my links to order, I’ll get a small kickback. So, if you’re inclined to order anything, feel free to click above.