如果结果有效但不需要,则在 python 中尝试失败的更好方法
Better way to fail a try in python if result is valid but not wanted
如果您在 python 中尝试,并且代码没有失败,但它超出了您想要的范围之类的,那么让它失败的最佳方法是什么,所以它会转到除了?
一个简单的例子如下,检查输入的是0到1之间的数字:
input = 0.2
try:
if 0 < float( input ) < 1:
print "Valid input"
else:
"fail"+0 (to make the code go to except)
except:
print "Invalid input"
有没有更好的方法来解决这个问题? between range 只是一个例子,所以它也应该与其他东西一起工作(同样,在上面的例子中,它也应该能够使用字符串格式的数字,所以检测类型不会真正起作用)。
内置的断言机制可能适合这里。
input = 0.2
try:
assert 0 < float( input ) < 1
print "Valid input"
except (AssertionError, ValueError):
print "Invalid input"
如果您提供给 assert
语句的条件未计算为 True
,则会引发 AssertionError
。此外,在尝试对无效值进行 float
转换时,会引发 ValueError
.
您可以使用raise
语句:
try:
if (some condition):
Exception
except:
...
请注意 Exception
可以更具体,例如 ValueError
,或者它可以是您定义的异常:
class MyException(Exception):
pass
try:
if (some condition):
raise MyException
except MyException:
...
另一个答案是准确的。但是为了让您更多地了解异常处理......您可以使用 raise
.
还要考虑 的评论,他说:
You also want to catch TypeError in case input is neither a string nor a number.
因此在这种情况下我们可以添加另一个 except 块
input = 1.2
try:
if 0 < float( input ) < 1:
print "Valid input"
else:
raise ValueError #(to make the code go to except)
except ValueError:
print "Input Out of Range"
except TypeError:
print "Input NaN"
TypeError
如果输入是一个对象(例如)
抱歉,rchang 的回答对于生产代码来说是不可靠的(如果 Python 是 运行 且带有 -O 标志,则跳过断言语句)。正确的解决办法是加一个ValueError
,即:
try:
if 0 < float(input) < 1:
raise ValueError("invalid input value")
print "Valid input"
except (TypeError, ValueError):
print "Invalid input"
如果您在 python 中尝试,并且代码没有失败,但它超出了您想要的范围之类的,那么让它失败的最佳方法是什么,所以它会转到除了?
一个简单的例子如下,检查输入的是0到1之间的数字:
input = 0.2
try:
if 0 < float( input ) < 1:
print "Valid input"
else:
"fail"+0 (to make the code go to except)
except:
print "Invalid input"
有没有更好的方法来解决这个问题? between range 只是一个例子,所以它也应该与其他东西一起工作(同样,在上面的例子中,它也应该能够使用字符串格式的数字,所以检测类型不会真正起作用)。
内置的断言机制可能适合这里。
input = 0.2
try:
assert 0 < float( input ) < 1
print "Valid input"
except (AssertionError, ValueError):
print "Invalid input"
如果您提供给 assert
语句的条件未计算为 True
,则会引发 AssertionError
。此外,在尝试对无效值进行 float
转换时,会引发 ValueError
.
您可以使用raise
语句:
try:
if (some condition):
Exception
except:
...
请注意 Exception
可以更具体,例如 ValueError
,或者它可以是您定义的异常:
class MyException(Exception):
pass
try:
if (some condition):
raise MyException
except MyException:
...
另一个答案是准确的。但是为了让您更多地了解异常处理......您可以使用 raise
.
还要考虑
You also want to catch TypeError in case input is neither a string nor a number.
因此在这种情况下我们可以添加另一个 except 块
input = 1.2
try:
if 0 < float( input ) < 1:
print "Valid input"
else:
raise ValueError #(to make the code go to except)
except ValueError:
print "Input Out of Range"
except TypeError:
print "Input NaN"
TypeError
如果输入是一个对象(例如)
抱歉,rchang 的回答对于生产代码来说是不可靠的(如果 Python 是 运行 且带有 -O 标志,则跳过断言语句)。正确的解决办法是加一个ValueError
,即:
try:
if 0 < float(input) < 1:
raise ValueError("invalid input value")
print "Valid input"
except (TypeError, ValueError):
print "Invalid input"