[Tutor] python arthematics

Alan Gauld alan.gauld at btinternet.com
Fri Mar 23 01:14:30 CET 2012


On 22/03/12 22:14, Sukhpreet Sdhu wrote:
> i want to write a program that reads simple arithematic expressions and
> calculates the result.

OK, there are many ways to do this but they pretty much
fall into three categories:

1) read the string and exec() it - easy but very
    risky from a security point of view.

2) Write a general text parser to break the input
    string into operands and operators and combine
    the results.

3) build a state machine that looks for valid input
   (this will be easier if you opt for reverse polish
    notation BTW)

You can do No 1 real quick just for fun, but don't try
that in a real world program.

So that leaves 2 and 3. If you understand the concepts
(or research them on wikipedia) you can have at it,
write some code and lets see what you get to.
Hint: Start with a limited subset - only 2 operands and
one operator allowed, say.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list