|
1 | 1 | """ |
2 | 2 | Written by: Shreyas Daniel - github.com/shreydan |
3 | | -Description: Uses Pythons eval() function |
| 3 | +Description: Uses Pythons eval() function |
4 | 4 | as a way to implement calculator |
5 | 5 |
|
6 | 6 | Functions available: |
|
22 | 22 |
|
23 | 23 |
|
24 | 24 | def main(): |
25 | | - |
| 25 | + |
26 | 26 | def calc(k): |
27 | 27 |
|
28 | | - functions = ['sin', 'cos', 'tan', 'sqrt', 'pi'] |
29 | | - |
| 28 | + functions = ['sin', 'cos', 'tan', 'sqrt', 'pi'] |
| 29 | + |
30 | 30 | for i in functions: |
31 | 31 | if i in k.lower(): |
32 | 32 | withmath = 'math.' + i |
33 | 33 | k = k.replace(i, withmath) |
34 | | - |
| 34 | + |
35 | 35 | try: |
36 | 36 | k = eval(k) |
37 | 37 | except ZeroDivisionError: |
| 38 | + |
38 | 39 | print("Can't divide by 0") |
39 | 40 | exit() |
40 | 41 | except NameError: |
41 | 42 | print('Invalid input') |
42 | 43 | exit() |
43 | | - |
| 44 | + |
44 | 45 | return k |
45 | 46 |
|
46 | | - print("\nScientific Calculator\nEg: pi * sin(90) - sqrt(81)") |
| 47 | + def result(k): |
| 48 | + k = k.replace(' ', '') |
| 49 | + k = k.replace('^', '**') |
| 50 | + k = k.replace('=', '') |
| 51 | + k = k.replace('?', '') |
| 52 | + k = k.replace('%', '/100') |
| 53 | + |
| 54 | + print("\n" + str(calc(k))) |
| 55 | + |
| 56 | + print("\nScientific Calculator\nEg: pi * sin(90) - sqrt(81)\nEnter quit to exit") |
47 | 57 |
|
48 | 58 | if sys.version_info.major >= 3: |
49 | | - k = input("\nWhat is ") |
| 59 | + while True: |
| 60 | + k = input("\nWhat is ") |
| 61 | + if k == 'quit': |
| 62 | + break |
| 63 | + result(k) |
| 64 | + |
50 | 65 | else: |
51 | | - k = raw_input("\nWhat is ") |
| 66 | + while True: |
| 67 | + k = raw_input("\nWhat is ") |
| 68 | + if k == 'quit': |
| 69 | + break |
| 70 | + result(k) |
52 | 71 |
|
53 | | - k = k.replace(' ', '') |
54 | | - k = k.replace('^', '**') |
55 | | - k = k.replace('=', '') |
56 | | - k = k.replace('?', '') |
57 | | - k = k.replace('%', '/100') |
58 | 72 |
|
59 | | - print("\n" + str(calc(k))) |
60 | | - |
61 | 73 | if __name__ == '__main__': |
62 | 74 | main() |
0 commit comments