如果结果有效但不想要,在python中尝试失败的更好方法

时间:2015-01-12 14:52:24

标签: python string python-2.7

如果你在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"

还有更好的方法吗?范围之间只是一个例子,所以它也应该与其他东西一起工作(同样,在上面的例子中,它也应该能够使用字符串格式的数字,因此检测类型不会真正起作用。)

4 个答案:

答案 0 :(得分:3)

很抱歉,但rchang的答案对于生产代码来说是不可靠的(如果使用-O标志运行Python,则会跳过assert语句)。正确的解决方案是提出ValueError,即:

try:
    if 0 < float(input) < 1:
        raise ValueError("invalid input value")
    print "Valid input"
except (TypeError, ValueError):
    print "Invalid input"

答案 1 :(得分:1)

您可以使用raise声明:

try:
    if (some condition):
        Exception
except:
    ...

请注意,Exception可能更具体,例如ValueError,或者它可能是您定义的例外:

class MyException(Exception):
    pass

try:
    if (some condition):
        raise MyException
except MyException:
    ...

答案 2 :(得分:1)

另一个答案是准确的。但要教育您更多关于异常处理的信息......您可以使用raise

还要考虑Bruno的评论:

  

如果输入既不是字符串也不是数字,您还希望捕获TypeError。

因此,在这种情况下,我们可以添加另一个除了块

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

答案 3 :(得分:0)

内置的断言机制可能适用于此。

input = 0.2
try:
    assert 0 < float( input ) < 1
    print "Valid input"
except (AssertionError, ValueError):
    print "Invalid input"
如果您提供给AssertionError语句的条件未评估为assert,则会引发{p> True。此外,尝试对无效值进行float转换会引发ValueError