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
>>>
x='' does not mean x is None, but rather a str of length 0. Use x = None instead. And while this works, the code of OP would already work, if his x was really None, but from the comments you see that x is indeed not defined. With x undefined, your solution fails, too.if x, because things other than None can evaluate to False.x=0. What output do you expect?x > 0 condition, but the point is clear.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
xin your case?if x is not None and x > 0: print("Not None")+else: print(None)works for integers and strings and lists in py2.7xis not defined... Python basics, you have to initialize variables before you use them!