Если вы хотите создать простой калькулятор, вы можете попробовать реализовать алгоритм Shunting-yard .
Но если вы хотите использовать подход регулярных выражений, я все равно сделаю это немного по-другому:
import re
#In python functions/methods usually are lowercase
#and words are seperated by _ while classes use CamelCasing
def eval_step_by_step(expression):
"""Evaluates math expression. Doesn't do any error checking.
expression (string) - math expression"""
print expression
#For pretty formating.
expr_len = len(expression)
#While there's parentheses in the expression.
while True:
#re.match checks for a match only at the beginning of the string,
#while re.search checks for a match anywhere in the string.
#Matches all numbers, +, -, *, / and whitespace within parentheses
#lazily (innermost first).
contents = re.search("\(([0-9|\*|/|\+|\-|\s]*?)\)", expression)
#If we didn't find anything, print result and break out of loop.
if not contents:
#string.format() is the Python 3 way of formating strings
#(Also works in Python 2.6).
#Print eval(expression) aligned right in a "field" with width
#of expr_len characters.
print "{0:{1}}".format(eval(expression), expr_len)
break
#group(0) [match] is everything matching our search,
#group(1) [parentheses_text] is just epression withing parentheses.
match, parentheses_text = contents.group(0), contents.group(1)
expression = expression.replace(match, str(eval(parentheses_text)))
#Aligns text to the right. Have to use ">" here
#because expression is not a number.
print "{0:>{1}}".format(expression, expr_len)
#For example try: (4+3+(32-1)*3)*3
problem = raw_input("Input math problem: ")
eval_step_by_step(problem)
Он не совсем работает так же, как ваша функция, но вы можете легко внести изменения в вашу функцию, чтобы они соответствовали моей. Как видите, я также добавил много комментариев, чтобы объяснить некоторые вещи.