from functools import reduce def str2num(s): #考虑输入不全是数字的情况,应用try..except.. try: return eval(s) #eval():将字符串string对象转化为有效的表达式 #参与求值运算返回计算结果 except Exception as e: print('Error:This is a invalid expression of number!') def calc(exp): ss = exp.split('+') ns = map(str2num, ss) try: return reduce(lambda acc, x: acc + x, ns) except Exception as e: return 'invalid result' def main(): r = calc('100 + 200 + 345') print('100 + 200 + 345 =', r) r = calc('99 + 88 + 7.6') print('99 + 88 + 7.6 =', r) r = calc('99 + 88 + 2.a') print('99 + 88 + 2.a =', r) r = calc('99 + a8.3 + 2.f') print('99 + a8.3 + 2.f =', r) main()
Sign in to make a reply
郝仁E哥