4

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
Taras
  • 447
  • 2
  • 7
  • 18

3 Answers3

8

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
>>>
Ajay2588
  • 527
  • 3
  • 6
  • 1
    `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. – Christian König Nov 14 '18 at 07:27
  • In this case, be careful with `if x`, because things other than `None` can evaluate to `False`. – iz_ Nov 14 '18 at 07:29
  • Following up on @Tomothy32 - try your operator with `x=0`. What output do you expect? – Christian König Nov 14 '18 at 07:37
  • @Tomothy32, I read your comment. Yes, X must be defined prior this condition check. I agree with if x, that will fail as you said but here we have another check which evaluates is X value is greater than 0. In such case, >>> x = 'str' >>> x if x and len(x)>0 else None 'str' – Ajay2588 Nov 14 '18 at 07:37
  • @ChristianKönig Well... 0 isn't the best example because of the `x > 0` condition, but the point is clear. – iz_ Nov 14 '18 at 07:39
  • @ChristianKönig, if x=0, yet the condition fail and else loop be in effective. Because, 0>0 is false. >>> x = 0 >>> x if x and x>0 else None >>> – Ajay2588 Nov 14 '18 at 07:39
  • @Ajay2588 But, for strings, your answer doesn't say `len(x) > 0`, it says `x > 0`. But I guess it's implied it's a number because of the `x > 0`. Still, it's never bad to be more careful; `if x is not None` is more explicit. – iz_ Nov 14 '18 at 07:40
  • @ChristianKönig, you are right. However, in my reply to Tomothy, I have written that peace of code too. Let me add the same in my answer section too. – Ajay2588 Nov 14 '18 at 07:43
1

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

Willie Cheng
  • 7,679
  • 13
  • 55
  • 68
0

some code like:

if x and x > 0:
    pass
Moon.Hou
  • 45
  • 1
  • 8