【问题标题】:Divide by Zero Exception raised despite edge case尽管有边缘情况,但仍引发除以零异常
【发布时间】:2017-03-14 00:44:15
【问题描述】:

我试图在 python3.5 中手动处理除以零异常,但是,它一直忽略我的用户定义的情况并给出默认异常。我怎样才能避免这种情况?任何帮助表示赞赏。

注意:我使用列表作为堆栈,因此是最后一个,并且正在检查顶部元素是否为 0。此外,顺序是正确的 - 我故意将顶部元素作为分母

elif 'div' in command:
        if len(stack)!=0 and len(stack)!=1 and is_digit(stack[len(stack)-2]) and is_digit(stack[len(stack)-1]) and stack[len(stack)-1]!=0:
            op2 = stack.pop();
            op1 = stack.pop();
            stack.append(str( int(int(op1) / int(op2)) ) + '\n');
        else:
            stack.append(':error:\n');

这给了 ZeroDivisionError: 除以零 INSTEAD of :error:

【问题讨论】:

    标签: python python-3.x integer-division divide-by-zero


    【解决方案1】:
    >>> "0" == 0
    False
    

    您的 if 语句测试与 0 是否相等,但在进行计算之前您不会转换为 int,因此您的 != 测试总是会通过,因为它将字符串与一个整数。

    (这是假设您的堆栈输入是字符串;如果不是,那么您可能不需要 int() 调用 - 但事实上您将除法的结果作为字符串添加到堆栈中让我相信他们是。)

    【讨论】:

    • 非常感谢!即使我最初尝试与“0”进行比较,它也不起作用。但是,您的回答使我将 stack[len(stack)-1] 类型转换为 int ,效果很好
    • 它可能是"0\n",因此"0\n"不会与"0"比较。
    猜你喜欢
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 2020-01-14
    • 1970-01-01
    相关资源
    最近更新 更多