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) == 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With