Python Try-Except:为什么它没有捕获它?

时间:2015-04-22 23:04:05

标签: python try-except

我正试图抓住try / except,我似乎无法让它工作。我想让它停止为负数或更大的数字:

try:
    h > 0.
except:
    return "Your distance (", h, ") is negative"
try:
    h < 3700000.
except:
    return "Your distance (", h, ") is outside the range this model"
else:
    # Return Correct Value:
    return g0*(r/(r+h))**2

然而,无论我抛出什么价值,它都会一直走到尽头......我尝试过不同的东西,除了假装和其他东西,但它们都不起作用:

>>> print(earth_gravity(1))
1.0
9.80649692152011
>>> print(earth_gravity(-1))
-1.0
9.806503078481338

1 个答案:

答案 0 :(得分:3)

因为没有引发异常。使用if语句来检查条件的真实性。

if h > 0:
   ...
elif ...:
   ...
else:
   ...
相关问题