防止“除以零错误”的方法

问题描述

我正在运行这个:

for dataset in waycategory_values:
        if dataset['value'] in [1.0,2.0,3.0]: 
            total_highway_distance += dataset['distance']

    for dataset in waycategory_values:
        total_distance += dataset['distance']

    highway_perc = (total_highway_distance / total_distance)

    print(highway_perc)

total_distance 可能为零。是否有一种平稳的方法可以让脚本继续运行并在总距离为 0 时仅打印 0。我一直在考虑每次都将 +1 添加到 total_distance 中 - 但没有更好的方法吗?

在我看来,以下内容正在流传,但它不起作用:

if total_distance == 0:
    total_distance = 1

解决方法

它“不起作用”,因为您编写的代码没有使用您所说的逻辑。你用文字描述的内容是这样的:

# print 0 when the total distance is 0

if total_distance == 0:
    highway_perc = 0
else:
    highway_perc = total_highway_distance / total_distance

print(highway_perc)

您也可以在一行中执行此操作:

highway_perc = 0 if total_distance == 0 else total_highway_distance / total_distance