7

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
6
  • Please provide a minimal reproducible example that reproduces the problem and is runnable. What is x in your case? Commented Nov 14, 2018 at 7:06
  • 5
    Not reproduceable: if x is not None and x > 0: print("Not None") + else: print(None) works for integers and strings and lists in py2.7 Commented Nov 14, 2018 at 7:06
  • 3
    What is the exception? Commented Nov 14, 2018 at 7:07
  • NameError: name 'x' is not defined Commented Nov 14, 2018 at 7:11
  • 3
    That means... x is not defined... Python basics, you have to initialize variables before you use them! Commented Nov 14, 2018 at 7:19

3 Answers 3

9

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
>>>
Sign up to request clarification or add additional context in comments.

8 Comments

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.
In this case, be careful with if x, because things other than None can evaluate to False.
Following up on @Tomothy32 - try your operator with x=0. What output do you expect?
@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'
@ChristianKönig Well... 0 isn't the best example because of the x > 0 condition, but the point is clear.
|
2

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

Comments

0

some code like:

if x and x > 0:
    pass

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.