Skip to content

Python ternary elif | Example code

  • by

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

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


Output: Ferrari

But the question is this does the 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!")


Python ternary elif

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

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading