Python CLI Calculator

by Nevermore

Nevermore
:(){:|:&};:
Music
Posts: 8
Threads: 4
Joined: Oct 2015
Reputation: 2
10-28-2015, 10:25 PM
#24231 (1)
I made another version of this calculator on a different forum, but now that I've learned about lexing and parsing, I've decided to add some more elements to it that make it a bit more efficient.

Todo:
Code:
push from definitions to module

Features:
Code:
- CLI (duh)
- In-program help function
- Exception catching
- Fibonacci reference
- Formatted times tables
- Input history (unintentional but cool nonetheless)
- Exit function

Available operations:
Code:
+        addition
-        subtraction
/        division
*        multiplication
**        exponents
./        floor division w/ remainder

Source:

Code:
from sys import exit as e
import operator as op

def rem(a,b):
return "v: %s\n   r: %s" % (a // b,a % b)

ops={'+': op.add,'-': op.sub,'*': op.mul,'/': op.div,'**': op.pow,'%': op.mod,'./': rem}

def fib_to(n):
    fibs = [1, 1]
    for i in range(2, int(n)+1):
        fibs.append(fibs[-1] + fibs[-2])
    print", ".join(map(str, fibs))

def tables():
for row in range(1,13):
s = ''
for col in range(1,13):
s += '{:3} '.format(row * col)
print(s)

def interface():
m = raw_input("} ").split()
try:
if m == ["/?"]: print "/? Help\n/e Exit\n/f <n> Fibonacci series to <n>\n/x Multiplication tables"
elif m == ["/e"]: e()
elif "/f" in m: fib_to(m[1])
elif m == ["/x"]: tables()
else: print">>",str(ops[m[1]](float(m[0]),float(m[2])))
except IndexError:
print "Unknown command '%s'" % str(m[0])
except KeyError:
print "Invalid syntax: "+" ".join(m)
interface()

print "Nevermore's CLI Calculator:\n/? for help"
interface()

Commands (other than equations):

Code:
/? Help
/e Exit
/f <n> Fibonacci series to <n>
/x Multiplication tables