4

I'm using ternary operator for short conditional variable definition. I was wondering when the expression returned True instead given in the expression value.

>>> digits = '123456'

>>> conv_d = digits != None if int(digits) else None

>>> conv_d
>>> True

>>> int(digits)
>>> 123456

Explain to me please, how this happens? What is the logical difference between a ternary operator and regular conditional expression in Python?

4 Answers 4

7

int(digits) == 123456 which is a true-ish value. So conv_d = digits != None. Since digits is not None, conv_d is set to true.

You probably wanted this:

conv_d = int(digits) if digits is not None else None

Remember that a string containing something not a number will raise an exception though! If you prefer 0 or None for those values, write a small function:

def toint(s):
    try:
        return int(s)
    except (ValueError, TypeError):
        return None # or 0
Sign up to request clarification or add additional context in comments.

Comments

5

The Python conditional operator is not in the same order as in other languages. And you should never compare equality with None unless you're certain that you need to.

conv_d = int(digits) if digits is not None else None

Comments

0

Alternatives to ternary-operators:

conv_d = digits != None and int(digits) or None #short-circuiting; just wrong in this context as it doesn't work for digits = "0" - please see comment(s) below

or

conv_d = int(digits) if digits is not None else None

The second expression is clearer, hence preferred.

2 Comments

The first will fail if int(digits) is 0. Both will fail if digits doesn't compare equality fairly with None.
Thanks for catching the first error! The idea was simply to show that there were a couple of alternatives in Python to the missing ternary operator, so I simply assumed digits to be either an str composed of [0-9] or None (ThiefMaster's response covers this issue anyway). Given that, I agree that when comparing with None, "is not" is the preferred operator.
0

Notice how the keywords are placed. "X if Y else Z". "Y" is the part that follows "if", so it is the condition. "X if Y" is a perfectly valid (though less common) English construction meaning the same thing as "if Y, X", thus X is the expression evaluated when Y is satisfied. Z is the expression evaluated when Y is not satisfied, similarly.

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.