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?
int(digits) == 123456which is a true-ish value. Soconv_d = digits != None. Sincedigitsis notNone,conv_dis set to true.You probably wanted this:
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: