In Python, the ternary conditional operator is a shorthand way of writing an if-else
statement. It has the following syntax:
[on_true] if [expression] else [on_false]
Here,
[expression]
is the condition to be evaluated,[on_true]
is the value to be returned if the condition isTrue
, and[on_false]
is the value to be returned if the condition isFalse
.
For example, let’s say we want to check if a number is even or odd and print a message accordingly. We can use the ternary conditional operator like this:
num = 10
print(“even” if num % 2 == 0 else “odd”)
Here, the expression num % 2 == 0
is evaluated first. If it is True
, the string "even"
is returned, otherwise the string "odd"
is returned.
Multiple ternary operators can be chained together using parentheses. For example:
num = 10
print(“zero” if num == 0 else “positive” if num > 0 else “negative”)
Here, the first ternary operator checks if num
is 0
. If it is, the string "zero"
is returned. If it is not, the second ternary operator is evaluated, which checks if num
is greater than 0
. If it is, the string "positive"
is returned, otherwise the string "negative"
is returned.
It’s worth noting that while the ternary conditional operator can make code more concise, using it excessively or in complex expressions can make code harder to read and understand.
- sunny asked 1 month ago
- You must login to post comments
Please login first to submit.