Simple Python Calculator Code

Written: August 22, 2026

A first calculator is really an if/elif ladder (or match) plus careful division-by-zero handling. Keep the UI in the terminal until the logic is solid.

Working example

a = float(input("First number: "))
op = input("Operator (+ - * /): ").strip()
b = float(input("Second number: "))

if op == "+":
    result = a + b
elif op == "-":
    result = a - b
elif op == "*":
    result = a * b
elif op == "/":
    if b == 0:
        raise SystemExit("Cannot divide by zero")
    result = a / b
else:
    raise SystemExit("Unknown operator")

print("Result:", result)

Next steps

Wrap the logic in a function and loop until the user types q. That turns a one-shot script into a tiny REPL.

Keep learning

If this walkthrough on python calculator code helped, open the code again and change one input or assumption. Small experiments beat rereading the same example.

Want more step-by-step tutorials like this? Browse blog.xqa.io — and tell us which topic you want next.

Advertisement

Previous Article

Python Program to Calculate the Area of a Triangle

Next Article

Check if a String Contains a Substring in JavaScript

Write a Comment

Leave a Comment

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

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨