#1.try/except,想编写一个出错时能返回输入参数的一个float函数defattempt_float(x):try:
return float(x)
except: #except后不加任何指定错误,则如果出现任何错误后,都会执行except后的语句return x
attempt_float('some')
'some'
#2.try/except +someerror,后面指定的可以是一个错误,也可以是多个错误defattempt_float(x):try:
return float(x)
except ValueError:
return x
attempt_float((1,2))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-a1f7e5239136> in <module>()
----> 1 attempt_float((1,2))
<ipython-input-8-392841f26717> in attempt_float(x)
2 def attempt_float(x):
3 try:
----> 4 return float(x)
5 except ValueError:
6 return x
TypeError: float() argument must be a string or a number
#于是出现了ValueError之外的错误则添加一个:defattempt_float(x):try:
return float(x)
except (ValueError,TypeError):
return x