input: term of type str output: returns the result of the computed term. purpose: This function is the actual calculator and the heart of the application
(term)
| 31 | |
| 32 | |
| 33 | def calc(term): |
| 34 | """ |
| 35 | input: term of type str |
| 36 | output: returns the result of the computed term. |
| 37 | purpose: This function is the actual calculator and the heart of the application |
| 38 | """ |
| 39 | |
| 40 | # This part is for reading and converting function expressions. |
| 41 | term = term.lower() |
| 42 | |
| 43 | # This part is for reading and converting arithmetic terms. |
| 44 | term = term.replace(" ", "") |
| 45 | term = term.replace("^", "**") |
| 46 | term = term.replace("=", "") |
| 47 | term = term.replace("?", "") |
| 48 | term = term.replace("%", "/100.00") |
| 49 | term = term.replace("rad", "radians") |
| 50 | term = term.replace("mod", "%") |
| 51 | term = term.replace("aval", "abs") |
| 52 | |
| 53 | functions = [ |
| 54 | "sin", |
| 55 | "cos", |
| 56 | "tan", |
| 57 | "pow", |
| 58 | "cosh", |
| 59 | "sinh", |
| 60 | "tanh", |
| 61 | "sqrt", |
| 62 | "pi", |
| 63 | "radians", |
| 64 | "e", |
| 65 | ] |
| 66 | |
| 67 | for func in functions: |
| 68 | if func in term: |
| 69 | withmath = "math." + func |
| 70 | term = term.replace(func, withmath) |
| 71 | |
| 72 | try: |
| 73 | # here goes the actual evaluating. |
| 74 | term = eval(term) |
| 75 | |
| 76 | # here goes to the error cases. |
| 77 | except ZeroDivisionError: |
| 78 | print("Can't divide by 0. Please try again.") |
| 79 | |
| 80 | except NameError: |
| 81 | print("Invalid input. Please try again") |
| 82 | |
| 83 | except AttributeError: |
| 84 | print("Please check usage method and try again.") |
| 85 | except TypeError: |
| 86 | print("please enter inputs of correct datatype ") |
| 87 | |
| 88 | return term |
| 89 | |
| 90 |