python - 使用 If 语句检查是否有错误发生
问题描述
我正在尝试编写一个程序来为我解决有关参数方程的问题。我正在尝试执行以下操作:
我试图找到参数方程的 2 个答案。第一个答案将是正平方根。第二个答案将是负平方根。如果第一个平方根引发数学域错误,则不要找到第二个答案。这是我到目前为止所拥有的:
def hitsGround(vertical_velocity, y_coordinate):
h = vertical_velocity/-16/-2
k = -16*(h)**2 + vertical_velocity*(h) + y_coordinate
time = float(input("At what height do you want me to solve for time?: "))
try:
hits_height1 = math.sqrt((time - k)/-16) + h
except ValueError:
print("It won't reach this height.")
else:
print(f"It will take {hits_height1} seconds to hit said height.")
try:
hits_height2 = -math.sqrt((time - k)/16) + h
except ValueError:
print("There is no second time it will reach this height.")
else:
print(f"It will take {hits_height2} seconds to hit said height.")
有什么方法可以使用 if 语句来检查第一个方程是否引发数学域错误,以便我可以使它找不到第二个答案?谢谢!
解决方案
您不能使用if
; 测试运行时异常。这正是try-except
它的作用。但是,当直接定义非法操作时,您可以在尝试操作之前测试该sqrt
条件:
if (time - k)/-16 < 0:
# no roots
else:
# proceed to find roots.
推荐阅读
- c - 程序没有错误但仍然崩溃
- jupyter-notebook - Jupyter Notebook“笔记本已更改”不断出现
- javascript - 具有固定宽度和高度的项目的网格
- r - R : 从主脚本调用外部子程序 R 脚本以避免等待子程序
- python - CountVectorizer 不尊重正则表达式
- php - 内部 api 调用将 $_SERVER['REQUEST_METHOD'] 更改为 GET
- android - 从 Android Studio 终端运行 Android 模拟器
- python - pyQt 和 opencCV s pyQt 都存在并使程序崩溃
- algorithm - 多个负循环的贝尔曼福特算法
- r - 同一图上的多度分布