Python中的ValueError除外

Python中的ValueError除外,python,Python,是否有更好的方法编写此代码: def add (exe1, exe2): try: a = float (exe1) b = float (exe2) total = float (a + b) except ValueError: return None else: return total 您可以在try/except块(计算和return)中包含所有内容: 还要注意的是,函数的默认返回

是否有更好的方法编写此代码:

def add (exe1, exe2):
    try:
        a = float (exe1)
        b = float (exe2)
        total = float (a + b)
    except ValueError:
        return None
    else:
        return total

您可以在
try/except
块(计算和
return
)中包含所有内容:


还要注意的是,函数的默认返回值是
None
,因此第二个
返回值实际上不是必需的(您可以使用
pass
),但它会使代码更可读。

如果您觉得contextlib.suppress更可读,也可以使用它

from contextlib import suppress
def add(exe1, exe2):
    with suppress(ValueError):
        return float(exe1) + float(exe2)
请参阅文档

from contextlib import suppress
def add(exe1, exe2):
    with suppress(ValueError):
        return float(exe1) + float(exe2)