Python idiom for the expression "... if ... else ..."

How to write an expression shorter:

return '%.0f' % float_var if float_var else float_var

or

if float_var:
    return formatted_string
else:
    return None

Thank!

+5
source share
5 answers

The expression is <value> if <condition> else <other_value>already rather idiomatic - of course, more than in another example, and is probably preferable whenever it <value>is simple. This is a ternary Python operator, so if you were looking for something like <condition> ? <value> : <other_value>this does not exist.

If you are calculating <value>or <other_value>performing several steps, use a longer alternative if: ... else: ....

+21
source

I would use parentheses to make the expression more readable:

return ('%.0f' % float_var) if float_var else float_var

When I first saw him, I read it as

return '%.0f' % (float_var if float_var else float_var)

. , , .

BTW

if float_var:
    return formatted_string
else:
    return None

, None. , , False (False, 0, 0.0, "", [] ..), , , , , int, float .. , , , 0.0 float_var. :

return ('%.0f' % float_var) if isinstance(float_var, float) else None

:

try:
    return "%.0f" % float_var
except TypeError:
    return None

( longs), float.

+3
  • , .

    • >>> float_var = 4.5
      >>> '%.0f' % float_var if float_var else float_var
      '5' # This is a string
      >>> float_var = 0.0
      >>> '%.0f' % float_var if float_var else float_var
      0.0 # This is a float
      

      , .

    • , None "if float_var"? , "if foo is not None", "if foo", .

      , , . None - : . .

  • . . , , , .

    • - or. None , .
+2

If you are using an already using one v if c else u, you are already using the most readable and effective ternary operator.

There are other ways , but they suffer from readability.

+1
source
float_var and "%.0f" % float_vav

Isn't that awesome?

0
source

All Articles