我正在尝试使用python3
和exception handling
编写函数。
我认为ValueError
是检查值是否在给定范围内的正确工具,如here in python3 doc所示:
函数接收具有正确类型但值不合适的参数
所以,在这个我的小片段中,我希望使用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不是我的主要语言。
请给我一些见解。
答案 0 :(得分:1)
我认为你误解了ValueError
(一般来说,Exception
)是什么。
Exceptions
是一种方法,用于向其调用者发出信号,表明遇到了一些会阻止该方法按预期执行的严重错误情况。 Python的try-except-finally
控制结构为调用者提供了一种检测错误条件并做出相应反应的方法。
ValueError
是由各种方法引发的标准Exception
,它们执行某种范围检查以表示提供给方法的值超出有效范围。换句话说,它是发出错误情况的通用方式。 ValueError
本身并不做任何检查。还有许多其他标准Exceptions
这样的; KeyError
表示您尝试访问不存在的映射结构中的密钥(如dict
或set
),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
的示例。