Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator return `True` instead the given value

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?

like image 345
I159 Avatar asked Dec 16 '22 07:12

I159


1 Answers

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
like image 199
ThiefMaster Avatar answered Dec 27 '22 13:12

ThiefMaster