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.

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.


Author picture
Rhett Trickett

Founder at Able

@rhett RhettTrickett rhetttrickett
Python

Join the discussion

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

Join with GitHub Join with Twitter