# L-17 MCS 275 Fri 19 Feb 2010 : evalexpr.py # evaluation of expressions def ExpressionStack(e): """ Returns a list to represent the stack of the expression. Spaces are removed. """ L = [] operators = ['+','-','*','/'] brackets = ['(',')'] operand = '' for c in e: if c in brackets + operators: if operand != '': L.append(operand) operand = '' L.append(c) elif c != ' ': operand = operand + c if operand != '': L.append(operand) return L def main(): """ prompts the user for a string and evaluates it """ e = raw_input('Give an expression : ') try: v = eval(e) print e, 'evaluates to', v except: print 'exception raised...' S = ExpressionStack(e) print 'the stack :', S main()