-1

I am trying to create a python programme that takes a function from the user (in terms of x) and returns its derivative using SymPy. However, when I enter letters other than x, SymPy throws an error of undefined symbols. I want it to treat letters apart from x as constant.

For example, if a user enters a*x**2 + bx, they should get 2*a*x + b, and if they enter z*x**2 + px, they should get 2*z*x + p. How can I treat letters apart from 'x' as constants without having to hard-code every letter as a symbol?

I hope my question is clear. Feel free to ask for any clarifications if required.

1 Answers1

1

You should first parse the user input and collect all symbols. To parse string to sympy expression use sympy.sympify. I assume you want to get derivative only W.R.T x. The full code will be:

import sympy as sp
expr = sp.sympify(input('enter expression: '))
print('Derivative w.r.t x: ', sp.diff(expr, 'x'))
d4riush
  • 370
  • 3
  • 8