Hello DEV Community 👋
I am currently diving deep into Python, focusing on strengthening my core programming logic. Today, I built a simple yet effective Terminal-Based Calculator.
While a basic calculator is a common beginner project, I wanted to ensure it didn't just run once and abruptly stop. I wanted it to feel like an actual software program.
✨ What I Built
A command-line calculator that performs basic arithmetic operations (Addition, Subtraction, Multiplication, Division) and continuously runs until the user explicitly commands it to stop.
🧠The Core Logic: The while Loop
The game-changer for this project was wrapping the main logic inside an infinite while True: loop. Instead of the terminal closing after one calculation, the program loops back, asking the user for their next operation.
Here is how I structured the workflow:
- User Menu: Display options (1 to 5).
-
Exit Condition: If the user selects '5', a
breakstatement gracefully exits the loop. -
Error Handling: Used a
try-exceptblock to catchValueErrorjust in case someone types a letter instead of a number. I also added a condition to preventZeroDivisionError.
💻 The Code
Here is the complete code for my calculator:
python
def start_calculator():
print("--- Python Terminal Calculator ---")
while True:
print("\nOperations:")
print("1. Add (+)")
print("2. Subtract (-)")
print("3. Multiply (*)")
print("4. Divide (/)")
print("5. Exit")
choice = input("Select an operation (1/2/3/4/5): ")
if choice == '5':
print("Shutting down... Goodbye! 👋")
break
if choice in ('1', '2', '3', '4'):
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Error! Please enter valid numbers only.")
continue
if choice == '1':
print(f"Result: {num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"Result: {num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"Result: {num1} * {num2} = {num1 * num2}")
elif choice == '4':
if num2 != 0:
print(f"Result: {num1} / {num2} = {num1 / num2}")
else:
print("Math Error! Cannot divide by zero.")
else:
print("Invalid Input! Please select a valid option.")
if __name__ == "__main__":
start_calculator()
Top comments (0)