GUI user input to function

Chris Angelico rosuav at gmail.com
Thu Dec 28 07:59:40 EST 2017


On Thu, Dec 28, 2017 at 11:06 PM, Nico Vogeli <nicco.9537 at gmail.com> wrote:
> Am Donnerstag, 28. Dezember 2017 12:59:24 UTC+1 schrieb Chris Angelico:
>> On Thu, Dec 28, 2017 at 8:38 PM, Nico Vogeli <nicco.9537 at gmail.com> wrote:
>> > Withs test, this return a correct value for the two x functions:
>> >
>> > from sympy import symbols
>> >
>> > x = symbols('x')
>> > f1 = eval(input('function 1 '))
>> > f2 = eval(input('function 2 '))
>> >
>>
>> What are you typing as input? It's hard to grok your code without knowing that.
>>
>> ChrisA
>
> I'm sorry! User input would look like this for example: x**2 + 3*x or x**3
>

Cool. That's an expression, but it isn't a function. To make that into
a function, you need to prefix it with the lambda keyword.

So you should be able to construct functions like this:

f1 = eval("lambda x: " + input("function 1: "))

Then, when you type "x**3", Python evaluates "lambda x: x**3", which
is a function.

ChrisA



More information about the Python-list mailing list