预防方法"divided by zero-error"

method to prevent "divided by zero-error"

我在运行这个:

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