簡體   English   中英

在這里使用嵌套的 try-except 可接受的 Python 樣式

[英]Is using nested try-except an acceptable Python style here

我需要檢查字符串price是整數還是浮點數,在這種情況下返回True否則返回False

這個函數是用可接受的 Python 風格編寫的嗎?

def is_valid_price(price):
    try:
        int(price)
        return True
    except:
        try:
            float(price)
            return True
        except:
            return False

如果不是,讓它看起來像 Pythony 的最好方法是什么?

絕對不是—— except沒有指定異常類很容易出問題。

def is_valid_price(price):
    try:
        float(price)
        return True
    except ValueError:
        return False

沒有必要使用 test int(price) ,因為如果字符串可以轉換為int ,它也可以轉換為浮點數。

在這種情況下,您只檢查價格類型:

def is_valid_price(price):
    return isinstance(price, (int, float))

is_valid_price(5)

您可以調用異常

assert float(price)

如果價格不是浮動(int)你會得到例外

ValueError Traceback (最近一次調用最后一次) in () ----> 1 assert float(price)

ValueError:無法將字符串轉換為浮點數:價格

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM