Error python : [ZeroDivisionError: division by zero]

前端 未结 1 1551
鱼传尺愫
鱼传尺愫 2021-02-13 09:39

I faced an error when I run my program using python: The error is like this:

ZeroDivisionError: division by zero

The visualization my program s

1条回答
  •  鱼传尺愫
    2021-02-13 09:48

    Catch the error and handle it:

    try:
        z = x / y
    except ZeroDivisionError:
        z = 0
    

    Or check before you do the division:

    if y != 0:
        z = x / y
    else:
        z = 0
    

    The latter can be reduced to:

    z = (x / y) if y != 0 else 0
    

    0 讨论(0)
提交回复
热议问题