Explain all ternary conditional operator in Python?

0
0

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 is True, and [on_false] is the value to be returned if the condition is False.

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.

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.