The ternary operator in Python, also known as the conditional expression, provides a concise way to perform conditional logic. It allows you to return a value based on a condition in a single line of code, making your code more readable and compact.
1. Syntax
value_if_true if condition else value_if_false
The ternary operator evaluates the condition
. If the condition is True
, it returns value_if_true
. If the condition is False
, it returns value_if_false
.
2. Examples
2.1 Basic Example
# Using the ternary operator to assign a value based on a condition
age = 18
status = "Adult" if age >= 18 else "Minor"
print(status) # Output: Adult
In this example, the ternary operator checks if age
is greater than or equal to 18. If it is, status
is set to “Adult”; otherwise, it is set to “Minor”.
2.2 Nested Ternary Operator
# Using nested ternary operators for multiple conditions
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C"
print(grade) # Output: B
This example demonstrates how to use nested ternary operators to handle multiple conditions. If score
is 85, the grade is set to “B” because it falls between 80 and 89.
2.3 Ternary Operator in Function Return
# Using the ternary operator to return a value from a function
def is_even(num):
return "Even" if num % 2 == 0 else "Odd"
print(is_even(4)) # Output: Even
print(is_even(7)) # Output: Odd
In this example, the ternary operator is used in the is_even
function to determine whether a number is even or odd and return the appropriate string.
3. Comparison with Traditional Conditional Statements
The ternary operator is a concise alternative to the traditional if-else
statement. Here’s how the previous examples would look using traditional conditional statements:
# Traditional if-else statement
age = 18
if age >= 18:
status = "Adult"
else:
status = "Minor"
print(status) # Output: Adult
# Nested if-else statement
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
print(grade) # Output: B
4. Summary
The ternary operator in Python offers a compact way to perform conditional logic and assign values based on a condition. It simplifies the code by reducing the need for multiple lines of conditional statements. While it is useful for simple conditions, it’s essential to use it judiciously to maintain code readability, especially when dealing with more complex conditions.