Programmer’s Notepad - Calculator Part 2

This time we’re going to use a PyPN script to evaluate maths expressions. We’re cheating a little, because we’re just going to ask python to evaluate a string and get a number back out.

import pn, scintilla

@script("Calculator")
def DoMaths():
    s = scintilla.Scintilla(pn.CurrentDoc())

    if s.SelectionEnd - s.SelectionStart < 1:
        return

    sel = s.SelText

    i = eval(sel)
    if type(i) in [int, float, complex]:
        pn.AddOutput(str(i))

To use this, simply select an expression like “5+5″ in the editor, run the script, and the output window will contain the evaluation of the expression.

This script is very simple, and in fact could be generalised to a python expression evaluator, but it serves the intended purpose well. It could also be adapted to make sure that expressions are of the form "exp=" and then put the result after the = sign, or perhaps to replace the selected expression with the result. These changes are left as exercises for the reader!

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*