Skip to content

Commit 4af51dd

Browse files
Merge pull request geekcomputers#164 from shreydan/master
added calculator.py
2 parents dc53fbe + ed59edb commit 4af51dd

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
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

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Written by: Shreyas Daniel - github.com/shreydan
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+
sine: sin(rad)
14+
cosine: cos(rad)
15+
tangent: tan(rad)
16+
square root: sqrt(n)
17+
pi: 3.141......
18+
"""
19+
20+
import math
21+
22+
def main():
23+
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)))
56+
57+
if __name__ == "__main__":
58+
main()

0 commit comments

Comments
 (0)