The ternary operator returns `True` instead of the given value

I use the ternary operator to define short conditional variables. I was wondering when the expression returns True instead of the value in the expression.

>>> digits = '123456' >>> conv_d = digits != None if int(digits) else None >>> conv_d >>> True >>> int(digits) >>> 123456 

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

+4
source share
4 answers

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

You probably wanted to:

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

Remember that a string containing something other than a number throws an exception! If you prefer 0 or None for these values, write a small function:

 def toint(s): try: return int(s) except (ValueError, TypeError): return None # or 0 
+7
source

The Python conditional statement is not in the same order as in other languages. And you should never compare equality with None unless you are sure what you need.

 conv_d = int(digits) if digits is not None else None 
+5
source

Alternatives to triple operators:

conv_d = digits! = None and int (digits) or None # short-circuiting; just wrong in this context as it does not work for numbers = "0" - see comment below

or

conv_d = int (digits) if the digits are not None else None

The second expression is clearer and therefore preferable.

0
source

Pay attention to how keywords are placed. "X, if Y is still Z." "Y" is the part that follows the "if", so this is a condition. "X if Y" is a perfectly valid (albeit less common) English construction, meaning the same as "if Y, X", so X is an expression evaluated when Y is executed. Z is an expression evaluated when Y is not satisfied, similarly.

0
source

Source: https://habr.com/ru/post/1379949/


All Articles