[Tutor] string conversion

Gregor Lingl glingl@aon.at
Sun, 18 Aug 2002 20:46:34 +0200


Andrea Valle schrieb:

>Dear List,
>I am creating a simple plotter for mathematical functions.
>Im my thoughts, I'd like to let the user give in input a string containing a
>mathematical function, i.e.
>
>from math import *
>function=input("function?\n")
>
>  
>
>>>>function?
>>>>"sin(x)"
>>>>        
>>>>
>
>How can I make some textual substition, so to convert the string 'function'
>in code? Is it possible?
>
>Hi Andrea!
>
At the moment I've only got two minutes to anser this.
(One could talk about it hours)

Try the following (and note the difference between
input and raw_input, which in essence is:
    input = raw_input+eval
 >>> from math import sin
 >>> x = 1.0
 >>> i = input("function? ")
function? sin(x)
 >>> i
0.8414709848078965
 >>> # this is sin(1.0)
 >>> f = raw_input("Funktion? ")
Funktion? sin(x)
 >>> f
'sin(x)'
 >>> eval(f)
0.8414709848078965
 >>> x = 0.5
 >>> eval(f)
0.47942553860420301
 >>>

Hope that helps. at least as an appetizer
Gregor