from functools import reduce
def str2num(s):
return int(s)
def calc(exp):
ss = exp.split('+')
ns = map(str2num, ss)
return reduce(lambda acc, x: acc+x, ns)
def main():
r = calc('100+200+345')
print('100+200+345=', r)
r =calc('99+88+7.6')
print('99+99+7.6=', r)
main()
print('END')
# 运行结果:
100+200+345= 645
Traceback (most recent call last):
File "/Users/pengchen/workspace/pythonProject1/错误、调试和测试/错误处理.py", line 17, in <module>
main()
File "/Users/pengchen/workspace/pythonProject1/错误、调试和测试/错误处理.py", line 14, in main
r =calc('99+88+7.6')
File "/Users/pengchen/workspace/pythonProject1/错误、调试和测试/错误处理.py", line 9, in calc
return reduce(lambda acc, x: acc+x, ns)
File "/Users/pengchen/workspace/pythonProject1/错误、调试和测试/错误处理.py", line 4, in str2num
return int(s)
ValueError: invalid literal for int() with base 10: '7.6'
这是QQ昵称