Categories We Write About

Build a terminal-based calculator

Creating a terminal-based calculator is a great way to practice programming fundamentals like input handling, basic operations, and control flow. Below is a Python example for a simple terminal calculator that supports addition, subtraction, multiplication, and division with continuous use until the user decides to exit.

python
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): if y == 0: return "Error! Division by zero." return x / y def calculator(): print("Simple Terminal Calculator") print("Operations: +, -, *, /") print("Type 'exit' to quit.n") while True: num1 = input("Enter first number: ") if num1.lower() == 'exit': print("Exiting calculator. Goodbye!") break num2 = input("Enter second number: ") if num2.lower() == 'exit': print("Exiting calculator. Goodbye!") break operation = input("Choose operation (+, -, *, /): ") if operation.lower() == 'exit': print("Exiting calculator. Goodbye!") break try: num1 = float(num1) num2 = float(num2) except ValueError: print("Invalid number input. Please enter valid numbers.n") continue if operation == '+': print(f"Result: {add(num1, num2)}n") elif operation == '-': print(f"Result: {subtract(num1, num2)}n") elif operation == '*': print(f"Result: {multiply(num1, num2)}n") elif operation == '/': result = divide(num1, num2) print(f"Result: {result}n") else: print("Invalid operation. Please choose +, -, *, or /.n") if __name__ == "__main__": calculator()

How it works:

  • The user inputs two numbers and an operation.

  • The program performs the operation.

  • If invalid input or operation is entered, it prompts the user again.

  • Type exit anytime to quit.

Would you like me to extend this with more functions or a more advanced interface?

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About