Python Program to Make a Simple Calculator
Beginner · Basics
A simple calculator takes two numbers and an operator (+, -, * or /) and prints the result. This program puts the calculation in a function and handles the two things that can go wrong: dividing by zero and an operator it does not know.
Program
12 + 4 = 16 12 - 4 = 8 12 * 4 = 48 12 / 4 = 3.0 12 / 0 = Error: cannot divide by zero 12 ^ 4 = Error: unknown operator ^
How it works
calculate()comparesoperatorwith each symbol in turn and returns the matching result.- Division checks
b == 0first, because dividing by zero would stop the program with aZeroDivisionError. - An operator that matches none of the four, like
^, falls through to theelsebranch and returns an error message. - The
/operator always gives a decimal result in Python 3, which is why 12 / 4 prints 3.0.
Another way to write it
Using match-case (Python 3.10 and later)
7 * 6 = 42 9 / 0 = Error: cannot divide by zero 2 % 5 = Error: unknown operator %
match compares the operator with each case in turn, and case _ catches everything else. It reads like a menu, but it needs Python 3.10 or newer.
Try it yourself
Add % for the remainder and ** for the power to the calculator, then test both.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
For a practical file: draw its flowchart or write its algorithm in steps.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises