Every now and then I need to get the answer to a calculation. As I usually have a terminal screen open that is a natural place for me to ask such mathematical questions.
The Python interactive shell is good for this purpose, provided you want to enter yet another shell only to have to exit out of it later on.
Sometimes though it is preferable to have the answer immediately available from the command line. Python has the -c command option that I found to be useful in processing a single command and returning the result. I wrote the following bash shell script to utilize it:
#!/bin/bash
# MHO 12-28-2014
#
# takes a equation from the command line, sends it to python and prints it
ARGS=0
#
if [ $# -eq 1 ]; then
ARGS=1
fi
#
if [ $ARGS -eq 0 ]; then
echo "pc - Python Command line calculator"
echo "ERROR: pc syntax is"
echo "pc EQUATION"
echo "Examples"
echo "pc 12.23+25.36 pc \"2+4+3*(55)\""
echo "Note: if calculating one single equation is not enough,"
echo "go elsewhere and do other things there."
echo "Enclose the equation in double quotes if doing anything fancy."
echo "m=math module ex. \"m.cos(55)\""
exit 1
fi
#
if [ $ARGS -eq 1 ]; then
eqn="$1"
python -c "import math; m=math; b=$eqn; print str(b)"
fi
#
$ pc 1/3.0
0.333333333333
$ pc 56*(44)
2464
$ pc 56*(44)*3*(6*(4))
177408
$ pc "m.pi*(2**2)"
12.5663706144
Question, keeping in mind python -c
option, is there any concise way to implicitly refer to the math module so that the last pc command might be formatted as pc "pi*(2**2)"
?
Python can be used as a calculator to compute arithmetic operations like addition, subtraction, multiplication and division. Python can also be used for trigonometric calculations and statistical calculations.
math is a built-in module in the Python 3 standard library that provides standard mathematical constants and functions. You can use the math module to perform various mathematical calculations, such as numeric, trigonometric, logarithmic, and exponential calculations.
Python can be used as a calculator to make simple arithmetic calculations. Simple arithmetic calculations can be completed at the Python Prompt, also called the Python REPL. REPL stands for Read Evaluate Print Loop. The Python REPL shows three arrow symbols >>> followed by a blinking cursor.
if [ $ARGS -eq 1 ]; then
eqn="$1"
python -c "from math import *; b=$eqn; print str(b)"
fi
$ pc "pi*(2**2)"
12.5663706144
Excellent! Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With