Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Does Python have a ternary conditional operator?

If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?

2 Answers

The answer is yes. Python has a ternary conditional operator. It allows testing a condition in a single line by replacing the multiline if-else which makes the code compact. The syntax is-
[on_true] if [expression]
else [on_false]

A simple way of using the ternary operator is as follows-
a, b = 10, 20
min = a if a < b else b

Here the output will be 10.
Another way of using a ternary operator is by using nested if-else-
a, b = 10, 20
print ("Both a and b are equal" if a ==b else "a is greater than b"
if a > b else "b is greater than a")
Yes, the concept of ternary operator was added in version 2.5.
For example,

>>> def find_max(a,b):
return a if (a>b) else b
>>> find_max(2, 3)

Login / Signup to Answer the Question.