-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

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."