Friday, May 25, 2018

Ternary expressions in Python

A ternary expression in Python allows you to combine an if-else block that produces
a value into a single line or expression. The syntax for this in Python is:

value = true-expr if condition else false-expr

Here, true-expr and false-expr can be any Python expressions. It has the identical
effect as the more verbose:

if condition:
    value = true-expr
else:
    value = false-expr


This is a more concrete example:

CODE:
x = 5
'Non-negative' if x >= 0 else 'Negative'

OUTPUT:
'Non-negative'

No comments:

Post a Comment