亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何檢查變量是否為數字(沒有數字)并在 Python 中不存在時引發錯誤?

如何檢查變量是否為數字(沒有數字)并在 Python 中不存在時引發錯誤?

慕田峪4524236 2023-01-04 14:26:02
我不明白為什么當半徑或高度是浮點數時以下內容無法正確運行并引發錯誤。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.")
查看完整描述

3 回答

?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

好像你想要

if not (isinstance(radius, int) or isinstance(radius,float)):

或者實際上

if not isinstance(radius, (float, int)):

目前你的邏輯是這樣的

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

所以,如果你有一個 int,那么你就會得到錯誤。如果你得到一個浮動,你就不會出錯,因為你最終得到False or (True == False)

任何事物or False都等同bool(Anything)于 ,在本例中,True == False,即False

此外,我建議首先提出所有錯誤并檢查條件。

然后只返回實際的數學,因為那時變量不可能是正的


查看完整回答
反對 回復 2023-01-04
?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

您可以將多種類型傳遞給isinstance,這樣您就可以擺脫or:


def cone(radius, height):

    if not isinstance(radius, (float, int)):

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

    if not isinstance(height, (float, int)):

        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.")


for value in [(1, 2), (0.33, 'foo')]:

    print(cone(*value))

輸出:


0.0

Traceback (most recent call last):

  File "/private/tmp/s.py", line 15, in <module>

    print(cone(*value))

  File "/private/tmp/s.py", line 5, in cone

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

TypeError: Error: parameters radius and height must be numeric.


查看完整回答
反對 回復 2023-01-04
?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

您的問題是if被評估為:


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

我想這不是你的意思。


無論如何,您實際上可以通過使用try/except. 您可以假設您的參數是數字并與 進行比較0。如果不是,將引發異常以便您可以捕獲它:


def cone(radius, height):

    try:

        if radius > 0 and height > 0:

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

        else:

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


    except TypeError:

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


查看完整回答
反對 回復 2023-01-04
  • 3 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號