When you call input()
, it simply returns a string of characters.
When you do eval()
on the returned string, the python interpreter will try to interpret that string as if it were python code. Anything that the user has written, will be interpreted at that moment as if it were written in the python language and was one more line of your program. The result of that evaluation will be assigned to your variable ecuacion
.
That means that the user can put for example: 2**3+4
and that will be interpreted as a python expression whose result in this case will be 12 and that would be what would go to the variable ecuacion
.
If the user instead writes something like 2*x**3 + 3*x
, then for python it's as if your program contains the line:
ecuacion = 2*x**3 + 3*x
Since the variable x
does not exist at this point, you get the error you saw: NameError: name 'x' is not defined
To fix this particular case, it is enough that this variable exists before the input. In the case of sympy
that variable must be a symbol so that it can later be used in operations such as the derivative. Therefore your program would be like this:
from sympy import Symbol
x = Symbol('x')
ecuacion = eval(input("Digite la funcion a evaluar:"))
ecuationdev = ecuacion.diff()
print(ecuationdev)
Note . This solves the particular problem that the user uses a x
as part of their expression, but not the general problem, since the user could use other letters that would continue to give you an error. In addition, it is necessary for the user to enter a valid python expression, such as 5*x
, since if the user instead writes something like 5x
that can be reasonable for a mathematician, eval()
will also produce an error when not be 5x
a valid python expression. You may be interested in viewing the documentation for parse_expr