如何在一行中做出這個聲明?if x is not None: if x > 0: pass如果我只用“和”寫,如果沒有,它會顯示異常if x is not None and x > 0: pass
3 回答

一只甜甜圈
TA貢獻1836條經(jīng)驗 獲得超5個贊
您還可以使用 python 三元運算符。在您的示例中,這可能對您有所幫助。您也可以進一步擴展相同的內(nèi)容。
#if X is None, do nothing
>>> x = ''
>>> x if x and x>0 else None
#if x is not None, print it
>>> x = 1
>>> x if x and x>0 else None
1
處理字符串值
>>> x = 'hello'
>>> x if x and len(x)>0 else None
'hello'
>>> x = ''
>>> x if x and len(x)>0 else None
>>>

HUX布斯
TA貢獻1876條經(jīng)驗 獲得超6個贊
Python 沒有特定的函數(shù)來測試是否定義了變量,因為所有變量都應(yīng)該在使用之前已經(jīng)定義,即使最初分配了 None 對象。嘗試訪問以前未定義的變量會引發(fā) NameError 異常(您可以使用 try/except 語句處理該異常,就像處理任何其他 Python 異常一樣)。
try: x
except NameError: some_fallback_operation( )
else: some_operation(x)
添加回答
舉報
0/150
提交
取消