如何检查变量是否为数字(没有数字)并在 Python 中不存在时引发错误?

我不明白为什么当半径或高度是浮点数时以下内容无法正确运行并引发错误。


def cone(radius, height):

    if isinstance(radius, int) or isinstance(radius,float) == False:

        raise TypeError("Error: parameters radius and height must be numeric.")

    if isinstance(height, int) or isinstance (height,float)== False:

        raise TypeError("Error: parameters radius and height must be numeric.")


    if radius > 0 and height > 0:

            return ((radius*radius)*(3.1415)*(height/3))

    if radius<=0:

        raise ValueError("Error: radius must be positive.")

    if height <=0:

        raise ValueError("Error: height must be positive.")


慕田峪4524236
浏览 118回答 3
3回答

蝴蝶不菲

好像你想要if&nbsp;not&nbsp;(isinstance(radius,&nbsp;int)&nbsp;or&nbsp;isinstance(radius,float)):或者实际上if&nbsp;not&nbsp;isinstance(radius,&nbsp;(float,&nbsp;int)):目前你的逻辑是这样的if&nbsp;isinstance(radius,&nbsp;int)&nbsp;or&nbsp;(isinstance(radius,float)&nbsp;==&nbsp;False):所以,如果你有一个 int,那么你就会得到错误。如果你得到一个浮动,你就不会出错,因为你最终得到False or (True == False)任何事物or False都等同bool(Anything)于 ,在本例中,True == False,即False此外,我建议首先提出所有错误并检查条件。然后只返回实际的数学,因为那时变量不可能是正的

慕神8447489

您可以将多种类型传递给isinstance,这样您就可以摆脱or:def cone(radius, height):&nbsp; &nbsp; if not isinstance(radius, (float, int)):&nbsp; &nbsp; &nbsp; &nbsp; raise TypeError("Error: parameters radius and height must be numeric.")&nbsp; &nbsp; if not isinstance(height, (float, int)):&nbsp; &nbsp; &nbsp; &nbsp; raise TypeError("Error: parameters radius and height must be numeric.")&nbsp; &nbsp; if radius > 0 and height > 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ((radius*radius)*(3.1415)*(height/3))&nbsp; &nbsp; if radius<=0:&nbsp; &nbsp; &nbsp; &nbsp; raise ValueError("Error: radius must be positive.")&nbsp; &nbsp; if height <=0:&nbsp; &nbsp; &nbsp; &nbsp; raise ValueError("Error: height must be positive.")for value in [(1, 2), (0.33, 'foo')]:&nbsp; &nbsp; print(cone(*value))输出:0.0Traceback (most recent call last):&nbsp; File "/private/tmp/s.py", line 15, in <module>&nbsp; &nbsp; print(cone(*value))&nbsp; File "/private/tmp/s.py", line 5, in cone&nbsp; &nbsp; raise TypeError("Error: parameters radius and height must be numeric.")TypeError: Error: parameters radius and height must be numeric.

心有法竹

您的问题是if被评估为:if (isinstance(radius, int)) or (isinstance(radius,float) == False)我想这不是你的意思。无论如何,您实际上可以通过使用try/except. 您可以假设您的参数是数字并与 进行比较0。如果不是,将引发异常以便您可以捕获它:def cone(radius, height):&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; if radius > 0 and height > 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ((radius*radius)*(3.1415)*(height/3))&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise ValueError("Error: radius and height must be positive.")&nbsp; &nbsp; except TypeError:&nbsp; &nbsp; &nbsp; &nbsp; raise TypeError("Error: parameters radius and height must be numeric.")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python