首页 > 解决方案 > 在这里使用嵌套的 try-except 可接受的 Python 样式

问题描述

我需要检查字符串price是整数还是浮点数,并True在这种情况下或False其他情况下返回。

这个函数是用可接受的 Python 风格编写的吗?

def is_valid_price(price):
    try:
        int(price)
        return True
    except:
        try:
            float(price)
            return True
        except:
            return False

如果没有,让它看起来像 Pythony 的最好方法是什么?

标签: pythonnestedtry-catch

解决方案


绝对不是——except不指定异常类很容易出现问题。

def is_valid_price(price):
    try:
        float(price)
        return True
    except ValueError:
        return False

不需要使用 test int(price),因为如果字符串可以转换为int,它也可以转换为浮点数。


推荐阅读