How make this statement in one line?
if x is not None:
if x > 0:
pass
if I write with just 'and' it shows exception if None
if x is not None and x > 0:
pass
How make this statement in one line?
if x is not None:
if x > 0:
pass
if I write with just 'and' it shows exception if None
if x is not None and x > 0:
pass
You can also use python ternary operator. In your example, this might help you. You can extend the same further too.
#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
Dealing with string values
>>> x = 'hello'
>>> x if x and len(x)>0 else None
'hello'
>>> x = ''
>>> x if x and len(x)>0 else None
>>>
Python doesn’t have a specific function to test whether a variable is defined, since all variables are expected to have been defined before use, even if initially assigned the None object. Attempting to access a variable that hasn’t previously been defined raises a NameError exception (which you can handle with a try/except statement, as you can for any other Python exception).
try: x
except NameError: some_fallback_operation( )
else: some_operation(x)
Reference :
Testing if a Variable Is Defined