![]() |
VOOZH | about |
Python offers a simple and concise way to handle conditional logic by using inline if, also known as the ternary operator or conditional expression. Instead of writing a full if-else block, we can evaluate conditions and assign values in a single line, making your code cleaner and easier to read for simple cases.
<expression_if_true> if <condition> else <expression_if_false>
Parameters:
Return Type: Result of expression_if_true if the condition is true, otherwise, result of expression_if_false.
Let's explore the different ways of using Inline if:
In this example, we are comparing and finding the minimum number by using the ternary operator.
Even
Explanation: This is not a ternary expression, but rather a one-line if statement.
In this example, if x is even, the variable message will be assigned the string "Even," and if x is odd, it will be assigned the string "Odd."
Even Odd
Explanation: If x % 2 == 0 is true, "Even" is assigned to message; otherwise, "Odd" is assigned.
In this example, we use nested inline if statements to determine the relationship between the values of x and y.
x is even and y is odd
Explanation: The code checks if x is even. If not, it checks y. If neither is true, it concludes both are odd.
Note: Nested inline if can reduce readability if overused.
In this example, we use inline if within a list comprehension to include only even numbers in the list of squares.
[4, 16, 36, 64, 100]
Explanation: Only even numbers are considered, and their squares are added to the list.
In this example, the operation variable is assigned the square function if n is even and the cube function if n is odd. The appropriate function is then called to calculate the result.
125
Explanation: Since n is odd, the cube function is selected and applied to n.