python3 ValueError值

标签 python exception-handling

我正在尝试使用 python3 编写一个函数,使用异常处理。 我认为 ValueError 是检查值是否在给定范围内的正确工具,如给定的 here in python3 doc其中说:

function receives an argument that has the right type but an inappropriate value

因此,在我的这个小片段中,我希望使用 ValueError 来检查未执行的范围 (0-1):

while True:
    try:
        imode = int(input("Generate for EOS(0) or S2(1)"))
    except (ValueError):
        print("Mode not recognised! Retry")
        continue
    else:
        break
print(imode)

产生:

Generate for EOS(0) or S2(1)3
3

当然,我可以像这样进行值检查:

if (imode < 0 or imode > 1):
    print("Mode not recogised. RETRY!")
    continue
else:
    break

但是 ValueError 似乎确实在做这件事。

这里有几个关于 ValueError 的问题,但没有一个检查“不适当的值,例如 this 我是新手,python 不是我的主要语言。 请给我一些见解。

最佳答案

我认为您误解了什么是 ValueError(通常是 Exception)。

Exceptions 是方法向其调用者发出信号的一种方式,表明已遇到某些严重错误情况,会阻止该方法按预期执行。 Python 的 try-except-finally控制结构为调用者提供了一种检测这些错误条件并做出相应 react 的方法。

ValueError 是一种标准的 Exception,由执行某种范围检查的各种方法引发,以表明提供给该方法的值超出了有效范围。换句话说,它是一种发出错误情况信号的通用方式。 ValueError 本身不做任何类型的检查。还有很多像这样的其他标准异常KeyError 表示您试图访问不存在的映射结构(如 dictset)中的键, IndexError 表示您试图将类似列表的结构索引到无效位置等。它们本身并没有真正做任何特殊的事情,它们只是一种直接指定确切问题类型的方法被调用的方法遇到。

Exceptions 与 python 中的成语密切相关,它通常被认为是 'easier to ask forgiveness than permission' .当然,许多语言都支持异常,但 Python 是为数不多的语言之一,您会经常看到代码中的 Exception 情况实际上是一种通常遵循的代码路径,而不是仅在发生某些事情时才会发生的代码路径真的错了。

下面是一个正确使用 ValueError 的例子:

def gen(selection):
    if imode == 0:
        # do EOS stuff here
    elif imode == 1:
        # do S2 stuff here
    else:
        raise ValueError("Please Select An Option Between 0-1")

def selector():
    while True:
        try:
            gen(int(input("Generate for EOS(0) or S2(1)")))
            break
        except ValueError as e: # This will actually satisfy two cases; If the user entered not a number, in which case int() raises, or if they entered a number out of bounds, in which chase gen() raises.
            print(e) 

请注意,可能有更直接的方法来执行您想要的操作,但这只是作为如何正确使用 ValueError 的示例。

关于python3 ValueError值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26978299/

相关文章:

python - 如何发送电子邮件附件?

python - 是否有一个 : keyed, 有序的 python 数据结构,并且可以通过键和顺序寻址?

r - 从 R 中的函数中捕获警告并仍然获得它们的返回值?

scala - 如何在 Scala 中具体化两个类次的重置?

python - 匹配多个单词Regex,python

python - SQL 请求无法使用 sqlparse 进行正确解析

python - 将 np.int8 数组与 127 相乘会根据平台产生不同的 numpy 数组类型

c# - "using exceptions to control flow"示例

c# - 在每个类的每个方法中尝试/捕获?

.net - 缺少自定义属性时选择正确的异常类型