Python ValueError的可能原因

时间:2015-04-11 17:29:05

标签: python debugging error-handling

我意识到我并没有提供很多细节,但这只是这种野兽的本质。

最近,当参与各种编码难题并使用Python时,我发现我用来解决大量测试数据的代码并未通过服务器上的所有测试。也就是说,我被告知代码会引发一个ValueError。

现在,这些挑战并没有告诉我任何比这更具体的原因,我不能分享我所写的代码,因为这会违背所述挑战的精神,反对规则。

但是对于那些比我更有经验的人来说,当我尝试扫描代码中潜在的ValueError导致错误时,我可以采用什么样的启发式方法?

官方Python文档只有这样说:

exception ValueError
Raised when a built-in operation or function receives an argument that has
the right type but an inappropriate value, and the situation is not
described by a more precise exception such as IndexError.

1 个答案:

答案 0 :(得分:1)

大多数情况下,当您尝试将字符串转换为数字时,会出现值错误,而该数字不是数字。例如:

>>> int("13a")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '13a'