Discuss / Python / 用C的人抓错误最顺手

用C的人抓错误最顺手

Topic source

from functools import reduce

def str2num(s): #字符串转数字  

    try:

        if('.' in s):   #通过判断小数点决定

            return float(s)

        else:           #没有小数点

            return int(s) 

    except BaseException as e:

        print('发生异常')

        logging.exception(e)

def calc(exp):  #函数

    ss = exp.split('+')#以+分隔

    print(ss)   #打印发现问题

    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 + 88 + 7.6 =', r)

main()

第一步用log处理,让程序出错了继续跑,暴露所有的问题。

再看出错地方是啥,再改。

_王若水

#3 Created at ... [Delete] [Delete and Lock User]

不用暴露,int 不行就直接上float

    try:
        return int(s)
    except Exception as e:
        return float(s)

  • 1

Reply