首页 > 解决方案 > 使用'try except'公式时出现ValueError

问题描述

我有一个清单:

['x', '-', '1', '=', '5']

这是我写的代码:

if (a[1]) == '+':
    try:
        print(int(int(a[0])+int(a[2])))
    except ValueError:
        print(int(int(a[0])+int(a[4])))
    except ValueError:
        print(int(int(a[2])+int(a[4])))

if (a[1]) == '-':
    try:
        print(int(int(a[0])-int(a[2])))
    except ValueError:
        print(int(int(a[0])-int(a[4])))
    except ValueError:
        print(int(int(a[4])-int(a[2])))

但是,此“尝试除外”显示以下错误并且无法运行。

Traceback (most recent call last):   File "Main.py", line 16, in <module>
    print(int(int(a[0])-int(a[2]))) ValueError: invalid literal for int() with base 10: 'x'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):   File "Main.py", line 18, in <module>
    print(int(int(a[0])-int(a[4]))) ValueError: invalid literal for int() with base 10: 'x'

谁能告诉我如何修复此代码?

当我使用列表运行时:

['1', '+', '3', '=', 'x']

这确实有效。

标签: pythonvalueerror

解决方案


这里的主要问题与您的例外有关!当使用多个时,每个都应该涵盖一个异常,并且您对两者都使用相同的异常,这会导致程序无法正常运行。

除此之外,您的代码还有一些问题(幸运的是,它们有一个简单的解决方案):
1)您使用了太多不需要的强制转换 int() -> 一旦使用 int(a[n]),它已经一个整数,因此无需在操作结果中重做它
2)您接收操作字符串并在算术运算符中转换它的逻辑过于复杂

为了解决这个问题,我的建议是:

import operator

operators = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.truediv,
    '%' : operator.mod,
    '^' : operator.xor,
}

# Got to find which are the digits to operate
numbersToOperate = [int(a[i]) for i in (0,2,4) if a[i].isdigit()]

if (a[0] == str(numbersToOperate[0])):
    print(operators[a[1]](numbersToOperate[0], numbersToOperate[1]))
else:
    print(operators[a[1]](numbersToOperate[1], numbersToOperate[0]))

推荐阅读