如何在python中检查变量是否不是None并且大于一行?

时间:2018-11-14 07:04:02

标签: python python-2.7

如何使这一陈述成行?

if x is not None:
    if x > 0:
        pass

如果我只写'and',则如果没有则显示异常

if x is not None and x > 0:
     pass

3 个答案:

答案 0 :(得分:1)

您还可以使用python三元运算符。在您的示例中,这可能会对您有所帮助。您也可以将其进一步扩展。

#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
>>>

答案 1 :(得分:1)

Python没有特定的功能来测试是否定义了变量,因为所有变量都应在使用前进行定义,即使最初分配了None对象也是如此。尝试访问以前未定义的变量会引发NameError异常(可以使用try / except语句来处理,就像处理其他任何Python异常一样)。

try: x
except NameError: some_fallback_operation(  )
else: some_operation(x)

参考:
Testing if a Variable Is Defined

答案 2 :(得分:0)

一些代码,例如:

if x and x > 0:
    pass
相关问题