ActiveState Code

Recipe 363786: RunningCalc


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
 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)

Comments

  1. 1. At 11:01 p.m. on 25 jan 2005, Fernando Perez said:

    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)
    
  2. 2. At 3:35 p.m. on 18 feb 2005, Shannon -jj Behrens (the author) said:

    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.

  3. 3. At 9:07 a.m. on 4 mar 2005, Tony Ha said:

    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..

Sign in to comment