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?
by

2 Answers

Shahlar1vxp
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
print(min)

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")
Sonali7
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)
3

Login / Signup to Answer the Question.