Python as Calculator

by
Annika Backstrom
in misc, on 9 May 2005. It is tagged #Linux and #Scripting.

As often as I need a calculator, I rarely have one within arm's reach. I do sit in front of thousands of dollars of computer equipment nearly all day, though, and if I can't do some arithmetic with it, well, what can I do?

I usually resort to bc, but I use it so rarely that I can never remember the correct syntax. bash is usually a good backup with its $((1 + 1)) syntax that I can use right from the shell prompt, but this particular method doesn't do floating point math. I did the find-a-suitable-calculator song and dance again today, but found a new partner this time: Python.

Python is a natural choice: it will return floating-point values without any additional steps, it retains a command history, and it allows for storing results in a variable. If you're handy with printf style statements, you can even format output to your liking. As an example:

annika@shed:~$ python
Python 2.4 (#1, Jan  1 2005, 21:33:55)
[GCC 3.3.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 7 * 19
133
>>> 3 / 21.0
0.14285714285714285
>>> print "%0.2f" % (81 / 2.1)
38.57
>>>