You can write an inline if statement (ternary conditional operator) using <value_true> if <condition> else <value_false> expression in Python. Here, it returns the value_true when if condition is satisfied, otherwise the value_false will be returned.
It is a concise way to write a conditional statement. You can write nested inline if statements, but make sure they won’t be as readable because they will get complicated as you go deeper.
Traditional if-else
if condition:
output = value_true
else:
output = value_false
Inline if statement (ternary operator)
output = value_true if condition else value_false
Example: Simple assignment based on condition
is_holiday = True activity = "Sleeping" if is_holiday else "Working" print(activity) # Output: "Sleeping"
Using an inline if in a function’s return value
Since it is a one-liner, you can use it with the return statement of a function. For example, the function accepts a value, and if it satisfies the “if condition”, its value is returned; otherwise, the “else” value is returned.
def get_discount(age):
return "Minor" if age < 18 else "Major"
print(get_discount(15))
# Output: Minor
Since the age is 15, it is less than 18, and that means it is a Minor.
Nested Inline if Statements
You can write a nested if-else statement inline using this syntax: <value1> if <condition1> else <value2> if <condition2> else <value3>.
score = 85 grade = "A" if score >= 90 else "B" if score >= 80 else "C" print(grade) # Output: B
You should limit nesting to 2 levels max for readability. Always prefer parentheses for clarity when nesting. If possible, always use a regular if…elif…else for more than two conditions.
Using the ternary operator with List Comprehension
If you are creating a list out of another list where you need transformation based on conditions, you can use the inline if-else in the list comprehension.
nums = [11, 21, 18, 19, 50] labels = ["Even" if n % 2 == 0 else "Odd" for n in nums] print(labels) # Output: ['Odd', 'Odd', 'Even', 'Odd', 'Even']
Inline if with Lambda Functions
If the condition is short and not complex, you can use the inline if-else with a lambda function, which itself is a shorter version of a regular function.
check_even = lambda x: "Even" if x % 2 == 0 else "Odd" print(check_even(19)) # Output: Odd print(check_even(50)) # Output: Even
With conditional expressions in a loop
Inside the for loop, you can use the inline if statement, and it works great, making your code smaller and readable, if not too complicated.
for i in range(5):
print("Even" if i % 2 == 0 else "Odd")
# Output:
# Even
# Odd
# Even
# Odd
# Even
That’s all!
