-2

How do you turn a string gathered from input into an actual function? For example,

    >>>function = input("Enter a function: ")
    >>>Enter a function: "sin(t)"

And then I'd be able to use the entered function. Is there a library to parse through the string and return a math function like so?

SorSorSor
  • 21
  • 6
  • you might just be stuck doing a long `if/elif/else` series for each operation you want to cover. – emsimpson92 Jun 21 '18 at 22:28
  • 1
    Parsing is nontrivial. No standard library does what you want to do. Doubtless people have written modules to do this, but asking for library recommendations is off-topic on Stack Overflow. – John Coleman Jun 21 '18 at 22:30
  • Welcome to [so]. It's really hard to tell what exactly you're asking for here. Please [edit] your question to include some expected input/output and any attempt you've made to solve the problem. – TemporalWolf Jun 21 '18 at 22:33

1 Answers1

1

You can use exec

>>> import math
>>> t=45
>>> exec('s=math.sin(t)')
>>> s
0.8509035245341184
>>> 

Or if you just want the function

>>> exec('f=math.sin')
>>> 
>>> f(45)
0.8509035245341184
>>> 
Sunitha
  • 11,777
  • 2
  • 20
  • 23
  • Link to similar question: https://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python – Will Jun 21 '18 at 22:30
  • 3
    What if the "string gathered from input" is malicious? In any event -- this doesn't address the question of how to turn the string into a function. Saying that the user can enter Python code which is then evaluated by `exec` in unlikely to be what OP had in mind. – John Coleman Jun 21 '18 at 22:32