Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python calculator - Implicit math module

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
#

Example Output

$ 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)" ?

like image 592
Micheal Owens Avatar asked Dec 29 '14 11:12

Micheal Owens


People also ask

Can Python be used as a calculator?

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.

What package is math in Python?

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.

Can Python be used as a calculator justify your answer?

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.


1 Answers

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!

like image 158
Micheal Owens Avatar answered Oct 28 '22 02:10

Micheal Owens