-2

I'm currently trying to let a user input their own equation for my calculator. If I run it with just my own equation, it works perfectly, however I can't get it to work from a user input. Any advice? Thanks This part of the code works

 def function(x):
     equation = 3*exp(x)
     return equation

When I change to a user input, It doesn't

 def function(x):
     equation = input('Insert your equation)
    return equation
SJ Rowell
  • 25
  • 3
  • You might want to look into the `eval` function. – Scott Hunter Feb 22 '21 at 16:05
  • I don't get why this question got downvoted. Many programmers who're learning Python often want to do this kind of a task. – spinlock Feb 22 '21 at 16:15
  • Does this answer your question? [Evaluating a mathematical expression in a string](https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – Peter O. Feb 22 '21 at 17:09

1 Answers1

3

You can use the eval() function. For example:

from math import exp


def function(x):
     equation = eval(user_input)
     return equation


user_input = "3*exp(x)"
x = 2
print(function(x))

But, citing realpython, "eval() is considered insecure because it allows you (or your users) to dynamically execute arbitrary Python code. This is considered bad programming practice because the code that you're reading (or writing) is not the code that you'll execute."

spinlock
  • 397
  • 1
  • 15