Python one-liner if-else statements
In this article I want to introduce conditional expressions also known as ternary operators.

Conditional expression to replace if-else statement
The term ternary means consisting of 3 parts, the 3 parts of a ternary operator or conditional expression are:
- value if condition is true
- the condition
- value if condition is false
Here is how you write it in Python:
value_if_True if condition else value_if_False
Before we make a conditional expression, we will look at an example of an if-else statment to set the value of a variable based on a condition:
result = 200
if result>0:
result_text = 'Profit'
else:
result_text = 'Loss'
print(result_text)This works fine and prints: Profit, but we can rewrite the middle part to make it 1 line of code instead of 4 by using a conditional expression.
The 3 parts of the conditonal expression are:
- value if condition is true:
'Profit' - the condition:
result>0 - value if condition is false:
'Loss'
With the 3 parts combined you get the conditional expression:
result = 200
result_text = 'Profit' if result>0 else 'Loss'
print(result_text)Conditional expression to replace if-elif-else statement
Maybe you spotted an error in our Profit or Loss expressions.
I wrote that if result is not higher than 0 result_text should be 'Loss'. But if the result is exactly 0 the result_text should actually be something like 'Break Even'.
We could implement that by specifying an extra condition. Here is an example of using the elif keyword in an if-else statement:
result = 0
if result>0:
result_text = 'Profit'
elif result==0:
result_text = 'Break Even'
else:
result_text = 'Loss'
print(result_text)This will correctly print: Break Even.
But now we are stuck with a long if-else statement. Or are we?
The answer is no, we can also write the above code to a one-liner. Let’s see it!
We start with the original conditional expression:
'Profit' if result>0 else 'Loss'Then we will remove the value_if_False, which is 'Loss' in our case:
'Profit' if result>0 elseAnd we will place another conditional expression as the value_if_False of the above expression:
'Profit' if result>0 else 'Break Even' if result==0 else 'Loss'Conditional expressions in Python statements
Besides it being way shorter, another advantage of conditional expressions is that you can also use them inside other Python statements.
For example, inside of a print statement:
print('Profit' if result>0 else 'Loss')Or in a calculation:
buy_product_a = True
spendings = 300
total_spendings = spendings + 200 if buy_product_a else 0Thank you for reading!
You can get full access to all my posts by joining Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium:
You might also like:





