sync - 10 months ago 54

Python Question

Could someone point me at the right direction on how to code a snippet in Python that, when launch by an user:

- prompts said user to input a polynomial function of x(e.g: 2*x)
- saves this input as a function of x, either by def or lambda (let's call this function f for clarity's sake)
- prompts user to input a number a
- calculates f(a)

I've always (and by always I mean somewhere around 3 months) used pre-computed functions, so interactive function inputs are something that I haven't tried (and therefore understood) yet. I suppose this will either end up at defining class for x, or using try-except, which both I never tried. The last two steps could be ignored if it's trivial matters.

Thanks!

Answer Source

Dynamic execution/evaluaion/compilation are available as funcitons exec, eval and compile.

There is an informative answer about these functions at http://stackoverflow.com/a/29456463/4997688