我想编写一个识别数学公式的程序,并要求用户输入数值并显示结果。
没有EVAL功能
我现在拥有的是:
formul=raw_input('Enter your formula: ")
a=input("Value a: ")
b=input("Value b: ")
c=input("Value c: ")
d=input("Value d: ")
答案 0 :(得分:1)
这是一个很好的,你可以使用eval并在每次有NameError时捕获。像这样的东西
import re
variables = {}
formula = raw_input('Insert formula: ')
while True:
try:
res = eval(formula, variables)
except NameError as e:
v = re.match('name .(\w+). is not defined', e.message).group(1)
variables[v] = input('insert value for %s: ' % v)
continue
print ("%s = %s" % (formula, res))
break
输出类似于
Insert formula: me + you
insert value for me: 10
insert value for you: 100
me + you = 110
答案 1 :(得分:0)
formula=formula.replace("a", str(a)).replace("b",str(b)).replace("c", str(c)).replace("d", str(d))
print eval(formula)