Simple Calculator Program in Python
Build a calculator in Python that adds, subtracts, multiplies and divides two numbers chosen by the user.
- Time
O(1) per calculation - Space
O(1) - Hints3
- Read4 min
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.
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.
First number, operator, second number, each on its own line.
"Result: <value>", or an error message.
Examples
12, +, 8Result: 20.0The numbers are read with float(), so the result is a float.
9, /, 0Error: cannot divide by zeroThe program checks b == 0 before dividing, so it does not crash.
Constraints
- Numbers may be integers or decimals
- The operator is one of +, -, *, /
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 /?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Calculator using if-else in Python
- Read
a, thenop, thenb. - Check
opwith anif-elifchain and do the matching operation. - In the
/branch, checkb == 0first. - Use
elsefor 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.
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.
Solution
Reveal the full Python solution
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.
O(1) per calculationO(1)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
Simple Calculator Program in Java
Hints · Dry run · SolutionSolve Similar problemSimple and Compound Interest Calculator
Hints · Dry run · SolutionSolve Similar problemStudent Grade Calculator Program in Python
Hints · Dry run · SolutionSolve Similar problemLeap Year Program in Python with Output
Hints · Dry run · SolutionSolve Related learningIf Else Statements
TutorialLearn Related learningFunctions For Beginners
TutorialLearn Related learningPython Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising Python for interviews?
CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
