如果变量不是None并且大于一行中的某些内容,如何检入python?

How to check in python if variable is not None and greater than something in one line?

如何在一行中声明?

1
2
3
if x is not None:
    if x > 0:
        pass

如果我只写"和",如果没有则显示异常

1
2
if x is not None and x > 0:
     pass


也可以使用python三元运算符。在您的示例中,这可能对您有所帮助。您也可以进一步扩展相同的内容。

1
2
3
4
5
6
7
#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

处理字符串值

1
2
3
4
5
6
>>> x = 'hello'
>>> x if x and len(x)>0 else None
'hello'
>>> x = ''
>>> x if x and len(x)>0 else None
>>>


一些代码如下:

1
2
if x and x > 0:
    pass