Python ternary elif | Example code

The ternary operator has simply x if c else y condition statement.

is_fast = True
car = "Ferrari" if is_fast else "Sedan"

print(car)

Output: Ferrari

But the question is is this does ternary operator with an additional elif statement possible in Python?

Answer: Just using the ternary operator with an elif statement won’t work (it’ll throw a syntax error). But you can nest two ternary operators.

Python ternary elif example

Simple example code nesting multiple ternary operators.

x = 70
print("No") if x > 42 else print("Yes") if x == 42 else print("What!")

Output:

Python ternary elif

Do comment if you have any doubts and suggestions on this Python ternary topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.