Skip to content

Commit d81eb50

Browse files
author
shreydan
committed
updated calculator.py
1 parent a8a894a commit d81eb50

File tree

1 file changed

+50
-32
lines changed

1 file changed

+50
-32
lines changed

calculator.py

+50-32
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,58 @@
11
"""
22
Written by: Shreyas Daniel - github.com/shreydan
3-
Description: Uses Pythons infamous eval() function as a way to implement calculator
3+
Description: Uses Pythons eval() function
4+
as a way to implement calculator
5+
6+
Functions available:
7+
8+
+ : addition
9+
- : subtraction
10+
* : multiplication
11+
/ : division
12+
% : percentage
13+
sin: sine(rad)
14+
cos: cosine(rad)
15+
tan: tangent(rad)
16+
sqrt: square_root(n)
17+
pi: 3.141......
418
"""
519

620
import math
721

8-
9-
def calc(k):
10-
11-
functions = ['sin','cos','tan','sqrt','pi']
12-
22+
def main():
1323

14-
for i in functions:
15-
if i in k.lower():
16-
withmath = 'math.' + i
17-
k = k.replace(i,withmath)
24+
def calc(k):
25+
26+
functions = ['sin','cos','tan','sqrt','pi']
27+
28+
for i in functions:
29+
if i in k.lower():
30+
withmath = 'math.' + i
31+
k = k.replace(i,withmath)
32+
33+
try:
34+
k = eval(k)
35+
except ZeroDivisionError:
36+
print ("Can't divide by 0")
37+
exit()
38+
except NameError:
39+
print ("Invalid input")
40+
exit()
41+
42+
return k
43+
44+
45+
print ("\nScientific Calculator\nEg: pi * sin(90) - sqrt(81)")
46+
47+
k = input("\nWhat is ")
48+
49+
k = k.replace(' ','')
50+
k = k.replace('^','**')
51+
k = k.replace('=','')
52+
k = k.replace('?','')
53+
k = k.replace('%','/100')
54+
55+
print ("\n" + str(calc(k)))
1856

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)))
57+
if __name__ == "__main__":
58+
main()

0 commit comments

Comments
 (0)