在Python中除以零返回零

在 Python 中使用 if/else 语句使除以零返回零,例如 return a / b if b else 0。当数除以 0 时,结果趋于无穷大,但我们可以检查除数是否等于 0,如果是则返回 0。

# ✅ make division of zero return zero using if/else

def handle_zero_division(a, b):
    return a / b if b else 0


print(handle_zero_division(15, 5))  # ?️ 3.0

print(handle_zero_division(15, 0))  # ?️ 0

# -------------------------------------

# ✅ make division of zero return zero using try/except


def handle_zero_division_2(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        result = 0

    return result


print(handle_zero_division_2(15, 5))  # ?️ 3.0

print(handle_zero_division_2(15, 0))  # ?️ 0

在Python中除以零返回零

当我们除以 0 时,我们不清楚预期的值是什么,因此 Python 会抛出一个错误。

当我们将一个数除以 0 时,结果趋向于无穷大。

第一个示例使用内联 if/else 语句来检查除数是否为假。

由于 0 是唯一的数字假值,如果除数为假,则返回 0,否则返回 a 除以 b 的结果。

我们还可以在 if/else 语句中显式检查除数是否等于 0。

def handle_zero_division(a, b):
    return 0 if b == 0 else a / b


print(handle_zero_division(15, 5))  # 👉️ 3.0

print(handle_zero_division(15, 0))  # 👉️ 0

或者,您可以使用 try/except 语句。

要除以零返回零:

  1. 将除法包装在 try/except 语句中。
  2. except 块应该处理 ZeroDivisionError
  3. 在 except 块中将结果设置为 0。
def handle_zero_division_2(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        result = 0

    return result


print(handle_zero_division_2(15, 5))  # 👉️ 3.0

print(handle_zero_division_2(15, 0))  # 👉️ 0

try/except 块被称为“请求宽恕,而不是许可”。

我们尝试将数字 a 除以数字 b,如果得到 ZeroDivisionError,则运行 except 块。

在 except 块中,我们将结果变量设置为 0。

如果除数不存储 0 值,则永远不会运行 except 块。