|
1 | 1 | """ |
2 | 2 | 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...... |
4 | 18 | """ |
5 | 19 |
|
6 | 20 | import math |
7 | 21 |
|
8 | | - |
9 | | -def calc(k): |
10 | | - |
11 | | - functions = ['sin','cos','tan','sqrt','pi'] |
12 | | - |
| 22 | +def main(): |
13 | 23 |
|
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))) |
18 | 56 |
|
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