forked from GodSuperK/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.py
74 lines (56 loc) · 1.43 KB
/
calculator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
Written by: Shreyas Daniel - github.com/shreydan
Description: Uses Pythons eval() function
as a way to implement calculator
Functions available:
+ : addition
- : subtraction
* : multiplication
/ : division
% : percentage
sine: sin(rad)
cosine: cos(rad)
tangent: tan(rad)
square root: sqrt(n)
pi: 3.141......
"""
import math
import sys
def main():
def calc(k):
functions = ['sin', 'cos', 'tan', 'sqrt', 'pi']
for i in functions:
if i in k.lower():
withmath = 'math.' + i
k = k.replace(i, withmath)
try:
k = eval(k)
except ZeroDivisionError:
print("Can't divide by 0")
exit()
except NameError:
print('Invalid input')
exit()
return k
def result(k):
k = k.replace(' ', '')
k = k.replace('^', '**')
k = k.replace('=', '')
k = k.replace('?', '')
k = k.replace('%', '/100')
print("\n" + str(calc(k)))
print("\nScientific Calculator\nEg: pi * sin(90) - sqrt(81)\nEnter quit to exit")
if sys.version_info.major >= 3:
while True:
k = input("\nWhat is ")
if k == 'quit':
break
result(k)
else:
while True:
k = raw_input("\nWhat is ")
if k == 'quit':
break
result(k)
if __name__ == '__main__':
main()