Python's Ternary Operator

1 min read

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


value_a if condition else value_b


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.

Author picture
Rhett Trickett

Founder at Able

@rhett RhettTrickett rhetttrickett

Join the discussion

Able is a developer community where people build their coding knowledge and careers.

Join with GitHub Join with Twitter