Beginner · Console Apps · Packages: standard library only
Project 2: Simple Calculator
Build a safe command-line calculator that understands brackets, functions, variables and the last answer, using the ast module instead of eval().
What you will learn
- Parse maths text safely with the ast module
- Use dictionaries to map operators to functions
- Create and raise your own exception class
- Write a read-evaluate-print loop with commands
Prerequisites
- Operators and expressions
- Dictionaries
- Functions and return values
- Exceptions and custom exception classes
- Strings and string methods
- while loops
Packages and installation
Packages: standard library only.
Project structure
simple-calculator/
main.py # safe expression engine + prompt loopStep-by-step build
- Plan the engine (top of main.py). We need text in, number out. Python's eval() can run any code, so we use ast.parse and check every node ourselves.
- Make the operator tables. Dictionaries map ast.Add to operator.add and so on. Anything not in the table is rejected.
- Define CalcError. A tiny class that inherits Exception. All problems become CalcError so main.py handles only one kind.
- Write _eval. Check the node type: number, binary operation, unary minus, name or function call. Call _eval again on the parts (recursion).
- Write calculate and pretty. calculate parses the text and turns Python errors into friendly CalcError messages. pretty prints 4.0 as 4.
- Write the loop (bottom of main.py). Read a line, handle commands (help, history, quit), handle 'name = expression', then call calculate.
- Test bad input. Try 10 / 0, 7 //, and import os. Each should print an Error line and the calculator keeps running.
Complete source code
"""Safe calculator engine: evaluates maths text without using eval()."""
import ast
import math
import operator
# Allowed operators mapped to real functions
BINARY = {
ast.Add: operator.add, ast.Sub: operator.sub,
ast.Mult: operator.mul, ast.Div: operator.truediv,
ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod,
ast.Pow: operator.pow,
}
UNARY = {ast.UAdd: operator.pos, ast.USub: operator.neg}
# Allowed functions and constants
FUNCTIONS = {"sqrt": math.sqrt, "abs": abs, "round": round,
"sin": math.sin, "cos": math.cos, "log": math.log10}
CONSTANTS = {"pi": math.pi, "e": math.e}
class CalcError(Exception):
"""Raised for any problem with the user's expression."""
def _eval(node, memory):
"""Walk the syntax tree and compute the value."""
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in BINARY:
left = _eval(node.left, memory)
right = _eval(node.right, memory)
if type(node.op) is ast.Pow and abs(right) > 100:
raise CalcError("Exponent is too big.")
return BINARY[type(node.op)](left, right)
if isinstance(node, ast.UnaryOp) and type(node.op) in UNARY:
return UNARY[type(node.op)](_eval(node.operand, memory))
if isinstance(node, ast.Name):
if node.id in CONSTANTS:
return CONSTANTS[node.id]
if node.id in memory:
return memory[node.id]
raise CalcError(f"Unknown name: {node.id}")
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
and node.func.id in FUNCTIONS and not node.keywords):
args = [_eval(a, memory) for a in node.args]
return FUNCTIONS[node.func.id](*args)
raise CalcError("That is not allowed in a calculation.")
def calculate(text, memory=None):
"""Evaluate text like '2 * (3 + 4)'. Returns a number."""
memory = memory if memory is not None else {}
try:
tree = ast.parse(text.strip(), mode="eval")
return _eval(tree.body, memory)
except ZeroDivisionError:
raise CalcError("Cannot divide by zero.")
except SyntaxError:
raise CalcError("Invalid expression.")
except (ValueError, TypeError, OverflowError):
raise CalcError("Math error (check the numbers).")
def pretty(value):
"""Show 4.0 as 4 and long decimals with 10 digits at most."""
if isinstance(value, float):
if value == int(value) and abs(value) < 1e15:
return str(int(value))
return f"{value:.10g}"
return str(value)
HELP = """Type a calculation such as 2 + 3 * 4 or sqrt(16).
Functions: sqrt abs round sin cos log Constants: pi e
Use 'ans' for the last result, 'x = 5' to save a variable.
Commands: help, history, quit"""
def main():
memory = {"ans": 0}
history = []
print("Simple Calculator. Type help for help.")
while True:
try:
line = input("calc> ").strip()
except EOFError:
break
if not line:
continue
if line == "quit":
break
if line == "help":
print(HELP)
continue
if line == "history":
for i, item in enumerate(history, 1):
print(f"{i}. {item}")
continue
# Assignment like x = 5 * 2
name = None
if "=" in line:
name, _, line = (part.strip() for part in line.partition("="))
if not name.isidentifier() or name in ("ans", "pi", "e"):
print("Error: bad variable name.")
continue
try:
result = calculate(line, memory)
except CalcError as problem:
print(f"Error: {problem}")
continue
memory["ans"] = result
if name:
memory[name] = result
text = pretty(result)
history.append(f"{line} = {text}")
print(text if not name else f"{name} = {text}")
print("Goodbye!")
if __name__ == "__main__":
main()
Code explanation
Why not eval()
eval('__import__("os").system("...")') would run commands on your computer. By walking the syntax tree and allowing only maths nodes, user text can never run code.
Syntax tree
ast.parse('2 + 3 * 4', mode='eval') builds a tree where * is deeper than +. This gives correct operator order and brackets for free.
Recursion in _eval
For a BinOp node we evaluate the left and right child first, then apply the operator. The function calls itself until it reaches plain numbers.
Memory dictionary
memory holds 'ans' and user variables. ast.Name nodes are looked up in it, so 'pi * r ** 2' uses the saved r.
Error translation
calculate catches ZeroDivisionError, SyntaxError and others, and raises CalcError with simple words. The user never sees a traceback.
Assignment parsing
line.partition('=') splits at the first equals sign. Names are checked with isidentifier() so 'ans' or 'pi' cannot be overwritten.
Expected output
Simple Calculator. Type help for help.
calc> 14
calc> 20
calc> 2.5
calc> Error: Cannot divide by zero.
calc> 1024
calc> 13
calc> r = 3
calc> 28.27433388
calc> 56.54866776
calc> Error: Invalid expression.
calc> Error: Invalid expression.
calc> 1. 2 + 3 * 4 = 14
2. (2 + 3) * 4 = 20
3. 10 / 4 = 2.5
4. 2 ** 10 = 1024
5. sqrt(144) + 1 = 13
6. 3 = 3
7. pi * r ** 2 = 28.27433388
8. ans * 2 = 56.54866776
calc> Goodbye!
Common errors and solutions
Solution: You used a variable before saving it. Type x = 5 first.
Solution: Check brackets and operators, for example '7 //' is incomplete.
Solution: Only happens if you split the code into modules. Check the module file name and run Python from the project folder.
Solution: Only numbers, + - * / // % **, brackets and the listed functions work. This is the safety feature.
Ideas to improve the project
- Add more functions such as tan, factorial and ceil
- Save history to a file and load it at start
- Add a 'degrees' mode for sin and cos
- Support % as percent in a friendly way
- Build a Tkinter window that reuses the same calculate function