Skip to content
doubtly

2 answers

A simple calculator in Python reads two numbers and an operator, then uses if-elif-else to perform the chosen operation.

# Simple Calculator
def calculate(a, op, b):
    if op == '+':
        return a + b
    elif op == '-':
        return a - b
    elif op == '*':
        return a * b
    elif op == '/':
        if b == 0:
            return "Error: division by zero"
        return a / b
    else:
        return "Invalid operator"

while True:
    a = float(input("Enter first number: "))
    op = input("Enter operator (+, -, *, /): ")
    b = float(input("Enter second number: "))
    print("Result:", calculate(a, op, b))
    again = input("Calculate again? (y/n): ")
    if again.lower() != 'y':
        break
print("Thank you!")

How it works:

  • float(input(...)) converts the typed text into a number.
  • The function calculate() checks the operator with if-elif and returns the result; it also avoids division by zero.
  • The while True loop lets the user do several calculations; break ends it when the user types anything other than y.

Sample run: entering 12, *, 3 prints Result: 36.0.

Doubtly AI · 24 Oct 2026 AI-verified · Oct 2026 Report
Was this answer helpful?

Your answer

Log in or create a free account to answer this question.