Doubt about an error

0

I'm getting into the topic of derivatives in python but recently I'm having an inconvenience, it turns out that when I enter the function I get the following error:

  

NameError Traceback (most recent call last)   ---- > 3 equation = eval (input ("Type the function to evaluate:"))

     

in ()

     

NameError: name 'x' is not defined

from sympy import Symbol

ecuacion = eval(input("Digite la funcion a evaluar:"))
ecuationdev = ecuacion.diff(i=Symbol('x'))

print(ecuationdev)

The truth if someone can tell me that I am doing wrong would be eternally grateful because I must deliver a job very soon regarding derivatives and I am very lost with it.

    
asked by Da Ni El 14.03.2018 в 04:30
source

1 answer

0

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

    
answered by 14.03.2018 в 10:56