Welcome, guest | Sign In | My Account | Store | Cart

This is a trivial calculator "shell" with a running total. As trivial as it is, I find it to be more useful than a normal calculator when doing my checkbook because of the ever-present running total.

Sed is to Vi as RunningCalc is to Python

python ~/programming/python/hacks/RunningCalc.py $ 0.0+50 $ 50.0-10 $ 40.0*0 $ 0.0+5 $ 5.0-2 $ 3.0

Python, 16 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#!/usr/bin/env python

"""This is a trivial calculator "shell" with a running total."""

import sys


current = 0.0
while True:
    sys.stdout.write("$ %s" % current)
    try:
        current = eval(str(current) + raw_input())
    except (KeyboardInterrupt, EOFError):
        sys.exit(0)
    except Exception, e:
	sys.stderr.write("Error: %s\n" % e)

3 comments

Fernando Perez 19 years, 2 months ago  # | flag

A few improvements... Very nice little recipe, but I'm not sure it does what you intended it to (or I misunderstood it). It doesn't actually add (numerically) each new input. I've modified it a bit to correct this, and added a simple clear/quit pair of key commands.

import sys

print 'Type c to clear, otherwise all input is added to the running total.'
print 'Type q to quit.'

current = 0.0
while True:
    try:
        cmd = raw_input("$ %s > " % current)
        if cmd=='c':
            current = 0.0
            print '*** Running total cleared ***'
            continue
        elif cmd=='q':
            raise EOFError
        current = eval("%s + %s " % (current,cmd))
    except (KeyboardInterrupt, EOFError):
        print
        sys.exit(0)
    except Exception, e:
        sys.stderr.write("Error: %s\n" % e)
Shannon -jj Behrens (author) 19 years, 2 months ago  # | flag

Hmm, yes, my version is clever... I'm sorry, I should have been more clear. Here is an example:

$ 0.0+500 # Set initial balance.
$ 500.0-5 # Start subtracting amounts.
$ 495.0-3
$ 492.0*1.08 # Set tax, or something interesting.
$ 531.36*0 + 500 # Start over with a new balance.
$ 500.0*0 + len(filter(lambda x: x > 5, range(10)))
$ 4.0
^D

^D (i.e. end of input) exits.

Tony Ha 19 years, 1 month ago  # | flag

A few improvements..., Tony Ha. I like the print statments, but your version is not a "calculator shell" any more, it dose not take * 10 or / 5 etc..

Created by Shannon -jj Behrens on Wed, 19 Jan 2005 (PSF)
Python recipes (4591)
Shannon -jj Behrens's recipes (19)

Required Modules

Other Information and Tasks