Python's Ternary Operator

Ternary operators are known as conditional expressions in Python and can be used to condense simple if / else statements.

Syntax:

value_a if condition else value_b

Example:

sale = True
discount = 0.2 if sale else 0.0 print(discount) # 0.2

While this is a nice way to condense a multi-line if statement be aware that in practice you can very easily end up with a long, complex and less readable line for someone to understand. So use it sparingly when it genuinely will make your code easier and more concise to understand.