[Tutor] Advise...

Alan Gauld alan.gauld at freenet.co.uk
Wed Jan 26 23:36:05 CET 2005


> If the user must be able to enter in the function, then it would be
better
> to evaluate this once and turn it into some sort of function that
you can
> call inside the loop (it's the eval that is so expensive).  How to
do that
> depends a lot on how complex the possible functions can be (if
they'll only
> include 'x*+/-' and numbers, for example, it's not so tricky).

exp = raw_input('Type expression')
func = eval('lambda x: " + exp)

print func(42)


etc...

Or if you really can't grokm lambda:

exec('def func(x): return " + exp)

should do the same...

Alan G.



More information about the Tutor mailing list