I had the same problem.
The way I recommend you to handle it is to create a temporary Python file to store the function the user input. Here's an example I used in a program I wrote to draw representations of mathematical functions:
with open("function.py",'w') as file:
f=input('enter the function you want to draw example: 2*x+1 or e**x :\n')
file.write("from math import *\ndef f(x):\n\treturn "+f)
This will create a file containing the function I want to call.
Next, you must call the function you wrote in the file to your program:
from function import f
Now you can use your function as normal python function.
If you want, you can also delete the file where you stored your function using os.remove:
import os
os.remove("function.py")
To help you understand, here is my program to draw mathematical functions:
import numpy
import cv2
import os
from math import *
def generate(f,a,b,min,max,functionname='noname'):
ph=(b-a)/1920
pv=(max-min)/1080
picture=numpy.zeros((1080,1920))
for i in range(0,1920):
picture[1079-(int((f(a+(i+1)*ph)*1080/max))),i]=255
for i in range(1920):
picture[1079-(int((f(a+(i+1)*ph)*1080/max)))+1,i]=255
cv2.imwrite(functionname+'.png',picture)
with open("function.py",'w') as file:
f=input('enter the function you want to draw example: or e**x :\n')
file.write("from math import *\ndef f(x):\n\treturn "+f)
from function import f
os.remove("function.py")
d=input('enter the interval ,min ,max and the image file name. Separate characters with spacebar. Example: 0 1 0 14 exponontielle :\n').split(" ")
generate(f,int(d[0]),int(d[1]),int(d[2]),int(d[3]),d[4])