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

2024-04-19 15:42:28 发布

您现在位置:Python中文网/ 问答频道 /正文

如果你在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范围只是一个例子,所以它应该也适用于其他事情(同样,在上面的例子中,它还应该能够使用字符串格式的数字,所以检测类型不会真正起作用)。你知道吗


Tags: to方法代码程序示例inputif数字
3条回答

另一个答案是准确的。但是为了教你更多关于异常处理的知识。。。你可以用^{}。你知道吗

同时考虑一下Bruno的评论,他说:

You also want to catch TypeError in case input is neither a string nor a number.

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

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将在输入为对象时引发(例如)

您可以使用raise语句:

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

请注意,Exception可以更具体,例如,ValueError,也可以是您定义的异常:

class MyException(Exception):
    pass

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

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

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

相关问题 更多 >