Turning a string into an programatic mathematical expression
Steve Holden
steve at holdenweb.com
Wed Oct 20 04:46:06 CEST 2004
Daniel Bickett wrote:
> The title really says it all. I'm trying to take input from a user
> (intended to be a mathematical expression), from a text box for
> example, and evaluate it mathematically within the program. For
> clarification: the user inputs the string "4*5(3-3)", I would be
> interested in a straight-forward way to find the result of that, based
> only on a string. The follow-up question would be how to incorporate
> variables into the mix, however I'll leave it at that for now. Thanks
> for your time :)
>
> Daniel Bickett
Well, you can simply use input(), a horrendously dangerous function that
was designed (if that's the right word) in less security-minded times to
allow users to enter expressions which would be made available to the
program:
>>> print input("What: ")
What: 4*5*(3-3)
0
>>> print input("What: ")
What: 24+35/7
29
>>>
Don't know whether this will help. It's also possible to use variables
in your expressions:
>>> a=33
>>> b=15.5
>>> print input("What: ")
What: a/b
2.12903225806
>>>
Note that the inputs must be valid Python expressions, which
unfortunately removes the possiblity of your implied multiplication:
>>> print input("What: ")
What: 4*5(3-3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 0, in ?
TypeError: 'int' object is not callable
>>>
If this isn't going to help you then I'm afraid you'll have to get down
and dirty by parsing the expressions and evaluating them in detail.
regards
Steve
--
http://www.holdenweb.com
http://pydish.holdenweb.com
Holden Web LLC +1 800 494 3119
More information about the Python-list
mailing list