[英]Is using nested try-except an acceptable Python style here
我需要检查字符串price
是整数还是浮点数,在这种情况下返回True
否则返回False
。
这个函数是用可接受的 Python 风格编写的吗?
def is_valid_price(price):
try:
int(price)
return True
except:
try:
float(price)
return True
except:
return False
如果不是,让它看起来像 Pythony 的最好方法是什么?
绝对不是—— except
没有指定异常类很容易出问题。
def is_valid_price(price):
try:
float(price)
return True
except ValueError:
return False
没有必要使用 test int(price)
,因为如果字符串可以转换为int
,它也可以转换为浮点数。
在这种情况下,您只检查价格类型:
def is_valid_price(price):
return isinstance(price, (int, float))
is_valid_price(5)
您可以调用异常
assert float(price)
如果价格不是浮动(int)你会得到例外
ValueError Traceback (最近一次调用最后一次) in () ----> 1 assert float(price)
ValueError:无法将字符串转换为浮点数:价格
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.