How to Build a Calculator in Python (Without eval)
Published · 3 min read · By The Samsung Calculator editorial team
Three versions, increasing in ambition
Version one: a menu. Ask for two numbers and an operation, print the result. Twenty lines, and it teaches input validation — `float(input())` raises `ValueError` on anything unexpected, and handling that properly is most of the work.
Version two: an expression. Accept `12 + 5 * 3` as one string. This is where most tutorials reach for `eval()` and where you should not.
Version three: a parser. Tokenise the string, convert to postfix with the shunting-yard algorithm, then evaluate the postfix with a stack. About sixty lines, and it is the same approach a real language interpreter takes.
Shunting-yard, in five rules
Read tokens left to right. A number goes straight to the output. An operator pops operators of greater or equal precedence off the stack to the output, then pushes itself. An opening bracket pushes. A closing bracket pops until the matching open bracket. At the end, pop everything remaining.
That gives `12 5 3 * +` for the example above. Evaluating postfix is then trivial: push numbers onto a stack, and when you meet an operator pop two, apply, push the result. The number left on the stack is your answer.
Why not eval()
`eval()` runs arbitrary Python. A user typing `__import__('os').system('rm -rf ~')` gets exactly what they asked for. `ast.literal_eval()` is safe but only handles literals, not arithmetic expressions, so it does not solve this problem.
The other trap is `float` precision: `0.1 + 0.2 != 0.3` in Python too. For money, use `decimal.Decimal` with an explicit context, which is what it exists for.
Test with pytest
Parametrise a table of expression-and-expected pairs and assert on each. Include unbalanced brackets, division by zero, unary minus and an empty string. Twenty test cases take ten minutes and will outlast the code.
Where to take it next
Add variables, then functions, then a small standard library. At that point you have written an interpreter, and the next book you read on the subject will make a great deal more sense.
Questions this answers
- calculator tutorial python
- how make calculator in python
- how to create calculator in python
- how to make calculator in python
About this article
Written and reviewed by The Samsung Calculator editorial team. Every calculator is written against a published formula, reviewed against at least one independent reference implementation, and dated when it changes. Last updated August 3, 2026. Spotted an error? Tell us.
More in Build Your Own Calculator
How to Build a Calculator in JavaScript
A working browser calculator in about a hundred lines, and the operator-precedence problem that breaks almost every fir…