【问题标题】:ValueError during using 'try except'formula使用'try except'公式时出现ValueError
【发布时间】:2019-04-26 18:08:45
【问题描述】:

我有一个清单:

['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']

这确实有效。

【问题讨论】:

  • 您期望int('x') 等于多少?
  • 您也不需要有多个int 演员表。与另一个整数相加或减去的整数始终是整数。
  • 对于同一个 try 块有两个 except ValueError 块是没有意义的。
  • 附加的except ValueError 行不会捕获前面ValueError 中引发的附加异常,除了处理程序。您必须使用另一个 try ... except,嵌套。

标签: python valueerror


【解决方案1】:

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

除此之外,您的代码还存在一些问题(幸运的是,有一个简单的解决方案):
1) 你在不需要的情况下使用了太多的 cast 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]))

【讨论】:

  • 非常感谢。我希望我能成为像你一样的程序员
【解决方案2】:

错误发生在except内部,没有try处理except内部的错误,所以错误传播。

在异常中添加try,这样它们就不会出错。

【讨论】:

    猜你喜欢
    • 2022-09-01
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    相关资源
    最近更新 更多