How to evaluate a math expression given in string form?

There are a few different ways to evaluate a math expression given in string form:

  1. Use a library: One option is to use a library like SymPy or math.js, which can parse and evaluate a string representation of a math expression.

  2. Write your own parser: You could also write your own code to parse the string and evaluate the expression. This would involve breaking the string down into its individual tokens (e.g. numbers, operators) and then using those tokens to perform the necessary calculations.

  3. Use eval(): In Python, you can use the built-in eval() function to evaluate a string as a math expression. However, this is generally not recommended, as it can be insecure (since it will execute any arbitrary code passed to it) and is slower than other options.

Here is an example of how you might use SymPy to evaluate a math expression given in string form:

import sympy

def evaluate(expression):
    return sympy.sympify(expression).evalf()

print(evaluate('2 + 3'))  # prints 5
print(evaluate('sin(pi/2)'))  # prints 1