Read any function in runtime
Matt McCredie
mccredie at gmail.com
Fri Oct 23 12:39:40 EDT 2009
joao abrantes <senhor.abrantes <at> gmail.com> writes:
>
> Hey. I want to make a program like this:print "Complete the function
f(x)="then the user would enter x+2 or 1/x or any other function that only uses
the variable x. Then my python program would calculate f(x) in some points for
example in f(2),f(4).. etc . How can I do this?
>
check out 'eval' or 'exec'.
statement = raw_input("Complete the function f(x)=")
print eval(statement, {'x':2})
print eval(statement, {'x':4})
print eval(statement, {'x':6})
or with 'exec':
statement = raw_input("Complete the function f(x)=")
exec "f = lambda x:"+statement in {}
print f(2)
print f(4)
print f(6)
Matt McCredie
More information about the Python-list
mailing list