我需要检查字符串price是整数还是浮点数,在这种情况下返回True,否则返回False。
此函数是否以可接受的Python样式编写?
def is_valid_price(price):
try:
int(price)
return True
except:
try:
float(price)
return True
except:
return False如果不是的话,怎样才能让它看起来像毕多尼?
发布于 2020-10-02 06:53:05
如果不指定异常类(Es),肯定不会- except很容易产生问题。
def is_valid_price(price):
try:
float(price)
return True
except ValueError:
return False不需要使用测试int(price),因为如果字符串可以转换为int,它也可以转换为浮动。
发布于 2020-10-02 06:53:41
在这种情况下,您只需检查价格类型:
def is_valid_price(price):
return isinstance(price, (int, float))
is_valid_price(5)您可以调用异常
assert float(price)如果价格不浮动(Int),你就会异常。
ValueError跟踪(最近一次调用)在() ->1断言浮点(价格) ValueError:无法将字符串转换为浮点数:
https://stackoverflow.com/questions/64167165
复制相似问题