Skip to content

Commit a8a894a

Browse files
author
shreydan
committed
added calculator.py
1 parent dc53fbe commit a8a894a

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,4 @@ In the scripts the comments etc are lined up correctly when they are viewed in [
5555

5656
- `timymodule.py` - A great alternative to Pythons 'timeit' module and easier to use.
5757

58-
58+
- `calculator.py` - Uses Python's eval() function to implement a calculator.

calculator.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Written by: Shreyas Daniel - github.com/shreydan
3+
Description: Uses Pythons infamous eval() function as a way to implement calculator
4+
"""
5+
6+
import math
7+
8+
9+
def calc(k):
10+
11+
functions = ['sin','cos','tan','sqrt','pi']
12+
13+
14+
for i in functions:
15+
if i in k.lower():
16+
withmath = 'math.' + i
17+
k = k.replace(i,withmath)
18+
19+
try:
20+
k = eval(k)
21+
except ZeroDivisionError:
22+
print ("Can't divide by 0")
23+
exit()
24+
except NameError:
25+
print ("Invalid input")
26+
exit()
27+
28+
return k
29+
30+
31+
print ("\nScientific Calculator\nEg: pi * sin(90) - sqrt(81)")
32+
33+
k = input("\nWhat is ")
34+
35+
k = k.replace(' ','')
36+
k = k.replace('^','**')
37+
k = k.replace('=','')
38+
k = k.replace('?','')
39+
40+
print ("\n" + str(calc(k)))

0 commit comments

Comments
 (0)