Python Ternary Operator
In Python, the ternary operator is a concise way of writing simple conditional expressions. It allows you to write an expression with a compact syntax that evaluates to one of two values based on a condition. The syntax of the ternary operator is as follows:
|
1 |
value_if_true if condition else value_if_false |
Here’s how it works:
- The
conditionis evaluated first. - If the
conditionisTrue, thevalue_if_trueis returned. - If the
conditionisFalse, thevalue_if_falseis returned.
Example 1: Simple ternary operator
|
1 2 3 |
x = 10 result = "Positive" if x > 0 else "Non-positive" print(result) # Output: "Positive" |
Example 2: Using ternary operator to assign variables
|
1 2 3 |
temperature = 25 weather = "Hot" if temperature > 30 else "Warm" print(weather) # Output: "Warm" |
Example 3: Using ternary operator for calculations
|
1 2 3 4 |
x = 12 y = 8 max_value = x if x > y else y print(max_value) # Output: 12 |
It’s essential to use the ternary operator judiciously to keep code readable. If the expression becomes too complex, it might be better to use traditional if-else blocks for better readability and maintainability.
Example: Check if a number is even or odd using the ternary operator.
|
1 2 3 4 5 6 7 8 |
# Input number num = 7 # Check if the number is even or odd using the ternary operator result = "Even" if num % 2 == 0 else "Odd" # Output the result print(f"The number {num} is {result}.") |
In this example, we have a variable num containing the input number 7. We use the ternary operator to check if the number is even or odd. The condition num % 2 == 0 checks whether the remainder of num divided by 2 is 0. If it’s 0, the number is even, and "Even" is assigned to the variable result. Otherwise, the number is odd, and "Odd" is assigned to result.
When we run this code, it will output:
The number 7 is Odd.
In this case, since 7 is not divisible by 2, it is considered odd, and the ternary operator assigns "Odd" to the variable result.
