Skip to content
Python project #24Advanced

Expression Evaluator

A recursive-descent parser for arithmetic with correct precedence, right-associative powers, variables, constants, functions and errors that point at the exact position.

Estimated time
~5 hours to build
Files
4 files · 377 lines
Technologies
Python 3, re, math

Introduction

Calculators, spreadsheets and programming languages all parse expressions. Writing a recursive-descent parser by hand — one function per grammar rule — is the clearest way to understand precedence, associativity and good error reporting.

Problem statement

Evaluate lines such as '1 + 2 * 3', '(1 + 2) * 3', '2 ^ 3 ^ 2' and 'x = 10', with + - * / % ^, unary minus, parentheses, the constants pi and e, functions sqrt, abs, round, sin, cos, log, ln, max and min, and variables. Power binds tighter than unary minus and is right-associative. Errors such as division by zero, unknown names, bad syntax, wrong argument counts and assigning to constants must show a caret under the problem. 'vars' lists variables.

Objectives

  • Write a tokenizer that records positions
  • Implement a grammar as recursive functions
  • Handle precedence and associativity correctly
  • Report errors with exact positions

Features

  • Correct precedence and right-associative ^
  • Variables and assignment
  • Constants and built-in functions with argument checks
  • Caret-marked error messages
  • Variable listing

Concepts demonstrated

  • Formal grammars
  • Recursive-descent parsing
  • Tokenization
  • Error reporting

System architecture

tokenize uses one regular expression with named groups and records each token's position. Parser has a method per grammar rule — expr, term, factor, power, atom — each calling the next-higher-precedence rule, so precedence follows from the call structure. power parses its exponent with factor, making ^ right-associative and allowing 2 ^ -1. EvalError carries a position used to print the caret.

Folder structure

TextProject tree
expression-evaluator/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

200 lines
Pythonmain.py
"""Expression Evaluator: a recursive-descent parser for arithmetic with variables and functions.
Grammar (lowest to highest precedence):
statement := NAME '=' expr | expr
expr := term (('+' | '-') term)*
term := factor (('*' | '/' | '%') factor)*
factor := ('-' | '+') factor | power
power := atom ('^' factor)? right-associative, binds tighter than unary minus
atom := NUMBER | NAME | NAME '(' args ')' | '(' expr ')'
Commands: vars, quit.
"""
import math
import re
import sys
from dataclasses import dataclass
FUNCTIONS = {"sqrt": (math.sqrt, 1), "abs": (abs, 1), "round": (round, 1), "sin": (math.sin, 1),
"cos": (math.cos, 1), "log": (math.log10, 1), "ln": (math.log, 1), "max": (max, -1), "min": (min, -1)}
CONSTANTS = {"pi": math.pi, "e": math.e}
TOKEN = re.compile(r"\s*(?:(?P<number>\d+\.?\d*|\.\d+)|(?P<name>[A-Za-z_]\w*)|(?P<op>[-+*/%^(),=]))")
class EvalError(Exception):
def __init__(self, message: str, position: int):
super().__init__(message)
self.position = position
@dataclass
class Token:
kind: str
text: str
pos: int
def tokenize(source: str) -> list[Token]:
tokens, pos = [], 0
while pos < len(source):
if source[pos:].strip() == "":
break
m = TOKEN.match(source, pos)
if not m or m.end() == pos:
bad = len(source) - len(source[pos:].lstrip())
raise EvalError(f"unexpected character '{source[bad]}'", bad)
kind = m.lastgroup
tokens.append(Token(kind, m[kind], m.start(kind)))
pos = m.end()
tokens.append(Token("end", "", len(source)))
return tokens
class Parser:
def __init__(self, source: str, variables: dict[str, float]):
self.tokens = tokenize(source)
self.i = 0
self.vars = variables
@property
def tok(self) -> Token:
return self.tokens[self.i]
def take(self, text: str | None = None) -> Token:
token = self.tok
if text is not None and token.text != text:
found = f"'{token.text}'" if token.text else "the end"
raise EvalError(f"expected '{text}' but found {found}", token.pos)
self.i += 1
return token
def statement(self) -> tuple[str | None, float]:
if self.tok.kind == "name" and self.tokens[self.i + 1].text == "=":
name = self.take().text
if name in CONSTANTS or name in FUNCTIONS:
raise EvalError(f"'{name}' is built in and can't be assigned", self.tokens[self.i - 1].pos)
self.take("=")
value = self.expr()
self.finish()
self.vars[name] = value
return name, value
value = self.expr()
self.finish()
return None, value
def finish(self) -> None:
if self.tok.kind != "end":
raise EvalError(f"unexpected '{self.tok.text}'", self.tok.pos)
def expr(self) -> float:
value = self.term()
while self.tok.text in ("+", "-"):
op = self.take().text
value = value + self.term() if op == "+" else value - self.term()
return value
def term(self) -> float:
value = self.factor()
while self.tok.text in ("*", "/", "%"):
op = self.take()
right = self.factor()
if op.text in "/%" and right == 0:
raise EvalError("division by zero", op.pos)
value = value * right if op.text == "*" else value / right if op.text == "/" else value % right
return value
def factor(self) -> float:
if self.tok.text in ("-", "+"):
sign = -1 if self.take().text == "-" else 1
return sign * self.factor()
return self.power()
def power(self) -> float:
base = self.atom()
if self.tok.text == "^":
op = self.take()
exponent = self.factor()
try:
return base ** exponent
except OverflowError:
raise EvalError("result is too large", op.pos) from None
return base
def atom(self) -> float:
token = self.tok
if token.kind == "number":
self.take()
return float(token.text)
if token.text == "(":
self.take("(")
value = self.expr()
self.take(")")
return value
if token.kind == "name":
self.take()
if self.tok.text == "(":
return self.call(token)
if token.text in CONSTANTS:
return CONSTANTS[token.text]
if token.text in self.vars:
return self.vars[token.text]
raise EvalError(f"unknown variable '{token.text}'", token.pos)
found = f"'{token.text}'" if token.text else "the end of the input"
raise EvalError(f"expected a number, name or '(' but found {found}", token.pos)
def call(self, name: Token) -> float:
if name.text not in FUNCTIONS:
raise EvalError(f"unknown function '{name.text}'", name.pos)
func, arity = FUNCTIONS[name.text]
self.take("(")
args = [self.expr()]
while self.tok.text == ",":
self.take(",")
args.append(self.expr())
self.take(")")
if arity != -1 and len(args) != arity:
raise EvalError(f"{name.text}() takes {arity} argument(s), got {len(args)}", name.pos)
try:
return float(func(*args))
except ValueError:
raise EvalError(f"{name.text}() is undefined for {', '.join(fmt(a) for a in args)}", name.pos) from None
def fmt(x: float) -> str:
return str(int(x)) if x.is_integer() and abs(x) < 1e15 else f"{x:.10g}"
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line
def main() -> None:
variables: dict[str, float] = {}
print("Expression Evaluator - try: x = 2 ^ 3 ^ 2, sqrt(x) + max(1, 5, 3), vars, quit")
while True:
line = ask(">>> ")
if line is None or line.strip() == "quit":
break
if not line.strip():
continue
if line.strip() == "vars":
for name, value in sorted(variables.items()):
print(f" {name} = {fmt(value)}")
continue
try:
name, value = Parser(line, variables).statement()
print(f"{name} = {fmt(value)}" if name else fmt(value))
except EvalError as error:
print(" " * (4 + error.position) + "^")
print(f"Error: {error}")
if __name__ == "__main__":
main()

What each file does

main.py
The tokenizer, the recursive-descent Parser with evaluation, the error type and the REPL.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Expression Evaluator - try: x = 2 ^ 3 ^ 2, sqrt(x) + max(1, 5, 3), vars, quit
>>> 1 + 2 * 3
7
>>> (1 + 2) * 3
9
>>> 2 ^ 3 ^ 2
512
>>> -2 ^ 2
-4
>>> x = 10
x = 10
>>> y = x / 4 + 0.5
y = 3
>>> rate = 18 % 7
rate = 4
>>> total = (x + y) * (1 + rate / 100)
total = 13.52
>>> sqrt(16) + max(1, 7, 3) - min(4, 2)
9
>>> round(pi * 100) / 100
3.14
>>> 10 / (5 - 5)
^
Error: division by zero
>>> 2 + * 3
^
Error: expected a number, name or '(' but found '*'
>>> (1 + 2
^
Error: expected ')' but found the end
>>> z + 1
^
Error: unknown variable 'z'
>>> foo(3)
^
Error: unknown function 'foo'
>>> sqrt(-1)
^
Error: sqrt() is undefined for -1
>>> pi = 3
^
Error: 'pi' is built in and can't be assigned
>>> 7 & 2
^
Error: unexpected character '&'
>>> vars
rate = 4
total = 13.52
x = 10
y = 3
>>> quit
Input
1 + 2 * 3
(1 + 2) * 3
2 ^ 3 ^ 2
-2 ^ 2
x = 10
y = x / 4 + 0.5
rate = 18 % 7
total = (x + y) * (1 + rate / 100)
sqrt(16) + max(1, 7, 3) - min(4, 2)
round(pi * 100) / 100
10 / (5 - 5)
2 + * 3
(1 + 2
z + 1
foo(3)
sqrt(-1)
pi = 3
7 & 2
vars
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • 2 ^ 3 ^ 2 is 512 (right-associative) and -2 ^ 2 is -4.
  • total = (x + y) * (1 + rate / 100) evaluates to 13.52 using earlier variables.
  • Division by zero, '2 + * 3', a missing ')' and assigning to pi each show a caret under the problem.

Common errors

2 ^ 3 ^ 2 gives 64

Make ^ right-associative by parsing the right-hand side recursively, not in a loop.

-2 ^ 2 gives 4

Parse unary minus at a lower precedence than power, as factor() does.

Possible improvements

  • Add comparison and logical operators
  • Support user-defined functions: f(x) = x ^ 2
  • Compile expressions to bytecode instead of evaluating directly

Additional challenges

  1. 1Print the syntax tree of an expression.
  2. 2Add implicit multiplication: 2pi, 3(x + 1).
  3. 3Add exact fractions with the fractions module.

Built and tested it yourself? Mark it to update your dashboard.