Beginner Logical Thinking Python

Simple Calculator Program in Python

Build a calculator in Python that adds, subtracts, multiplies and divides two numbers chosen by the user.

  • TimeO(1) per calculation
  • SpaceO(1)
  • Hints3
  • Read4 min
Quick answer

A simple calculator in Python reads two numbers with float(input()) and an operator with input(). An if-elif chain checks the operator: + adds, - subtracts, * multiplies, and / divides after checking that the second number is not 0. Any other operator prints "Invalid operator". Moving the if-elif into a function, calculate(a, b, op), lets you reuse it and test it easily.

input and float conversionif-elif-elseFunctions with return valueswhile loop and try-except
1

Problem statement

Write a simple calculator program in Python. Read two numbers and an operator (+, -, * or /) from the user and print the result.

Show a clear error for division by zero and for an unknown operator. First write it with if-elif, then move the logic into a function.

Input

First number, operator, second number, each on its own line.

Output

"Result: <value>", or an error message.

Examples

Example 1
Input12, +, 8
OutputResult: 20.0

The numbers are read with float(), so the result is a float.

Example 2
Input9, /, 0
OutputError: cannot divide by zero

The program checks b == 0 before dividing, so it does not crash.

Constraints

  • Numbers may be integers or decimals
  • The operator is one of +, -, *, /
2

Think before you code

Reveal the questions to ask yourself first
  • input() always returns a string. What do you need to do before adding two numbers?
  • How will the program choose one of four operations?
  • What should happen if the second number is 0 and the operator is /?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Use float(input(...)) so both 5 and 2.5 are accepted.
2 Hint 2
Compare the operator with op == "+", then elif op == "-", and so on.
3 Hint 3
Inside the / branch, check if b == 0 first and print an error instead of dividing.
4

Approach

Reveal the step-by-step approach

Calculator using if-else in Python

  1. Read a, then op, then b.
  2. Check op with an if-elif chain and do the matching operation.
  3. In the / branch, check b == 0 first.
  4. Use else for any operator that did not match.
Operator Operation Example Result
+ a + b 12 + 8 20.0
- a - b 3 - 10 -7.0
* a * b 7 * 6 42.0
/ a / b 15 / 4 3.75

In Python 3, / always gives a float, even for 8 / 2. Use // for floor division and % for the remainder if your question asks for them.

For a refresher on the if-elif chain, see if-else statements in Python.

5

Dry run

Walk through the example step by step

Input 15, /, 4:

a = 15.0, op = "/", b = 4.0
op == "+"?  no
op == "-"?  no
op == "*"?  no
op == "/"?  yes
    b == 0? no
    print a / b = 3.75

Only one branch runs. The else is skipped because a branch already matched.

6

Solution

Reveal the full Python solution
solution.py
a = float(input("Enter first number: "))
op = input("Enter operator (+, -, *, /): ")
b = float(input("Enter second number: "))

if op == "+":
    print("Result:", a + b)
elif op == "-":
    print("Result:", a - b)
elif op == "*":
    print("Result:", a * b)
elif op == "/":
    if b == 0:
        print("Error: cannot divide by zero")
    else:
        print("Result:", a / b)
else:
    print("Invalid operator")

Sample runs:

Enter first number: 12
Enter operator (+, -, *, /): +
Enter second number: 8
Result: 20.0
Enter first number: 15
Enter operator (+, -, *, /): /
Enter second number: 4
Result: 3.75
Enter first number: 9
Enter operator (+, -, *, /): /
Enter second number: 0
Error: cannot divide by zero
Enter first number: 5
Enter operator (+, -, *, /): %
Enter second number: 2
Invalid operator

Results print as 20.0 because float() was used. If you only need whole numbers, use int() instead, but then input like 2.5 will raise an error.

Calculator program in Python using a function

A function separates the calculation from the input and output. It returns either the answer or an error message.

def calculate(a, b, op):
    if op == "+":
        return a + b
    elif op == "-":
        return a - b
    elif op == "*":
        return a * b
    elif op == "/":
        if b == 0:
            return "Error: cannot divide by zero"
        return a / b
    else:
        return "Invalid operator"


print(calculate(12, 8, "+"))
print(calculate(12, 8, "-"))
print(calculate(12, 8, "*"))
print(calculate(12, 8, "/"))
print(calculate(12, 0, "/"))
print(calculate(12, 8, "^"))
20
4
96
1.5
Error: cannot divide by zero
Invalid operator

Here the numbers are passed as integers, so +, - and * give integers and only / gives a float. return ends the function at once, so no else is needed after the b == 0 check. See functions for beginners for how parameters and return values work.

Keep the calculator running until the user quits

while True:
    op = input("Operator (+, -, *, /) or q to quit: ")
    if op == "q":
        print("Bye")
        break
    try:
        a = float(input("First number: "))
        b = float(input("Second number: "))
    except ValueError:
        print("Please enter numbers only")
        continue
    print("Result:", calculate(a, b, op))
Operator (+, -, *, /) or q to quit: *
First number: 2.5
Second number: 4
Result: 10.0
Operator (+, -, *, /) or q to quit: /
First number: ten
Please enter numbers only
Operator (+, -, *, /) or q to quit: -
First number: 100
Second number: 1
Result: 99.0
Operator (+, -, *, /) or q to quit: q
Bye

This uses the calculate() function from above. float("ten") raises ValueError, and except catches it so the program asks again instead of crashing. continue jumps back to the top of the loop, and break leaves it.

The Java version with switch is on simple calculator program in Java. For another formula-based program, see simple and compound interest calculator.

TimeO(1) per calculation
SpaceO(1)
7

Review before the interview

Common mistakes

  • Adding the inputs without float() or int(). "12" + "8" gives "128", not 20.
  • Writing if op == "+" or "-": which is always True, because the string "-" is truthy.
  • Dividing before checking b == 0, which raises ZeroDivisionError.
  • Using several separate if statements instead of elif, so the else runs even after a match.
  • Using eval() on user input to build a calculator. It can run any code the user types.

Edge cases to test

  • Second number 0 with /: print an error instead of dividing.
  • Unknown operator such as % or ^: falls through to the else branch.
  • Non-numeric input like "ten": float() raises ValueError; the loop version catches it.
  • Operator typed with spaces, like " + ": it will not match. Use op.strip() to remove them.

Interview follow-ups

  • How would you add % (remainder) and ** (power) to the calculator?
  • How would you rewrite the if-elif chain with a dictionary of functions?
  • How would you use match-case (Python 3.10+) instead of if-elif?

Keep practising

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us