简体   繁体   English

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

[英]method to prevent "divided by zero-error"

im running this:我正在运行这个:

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)

It is possible that total_distance is zero. total_distance 可能为零。 Is there a smooth way to keep the script going and just print 0 when the total distance is 0. I was thinking about adding +1 to total_distance everytime - but isn't there a better way?有没有一种流畅的方法可以让脚本继续运行,并且在总距离为 0 时只打印 0。我一直在考虑每次都将 +1 添加到 total_distance - 但没有更好的方法吗?

in my mind the below is circulating, but it's not working:在我看来,以下内容正在流传,但不起作用:

if total_distance == 0:
    total_distance = 1

It's "not working" because what the code you wrote doesn't use the logic you say you want.它“不起作用”,因为您编写的代码没有使用您所说的逻辑。 What you described in words looks like this:您用文字描述的内容如下所示:

# 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)

You can also do this in one line:您也可以在一行中执行此操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM