Python’s ternary operator

Well…I have to say, Python’s ternary operator was kinda annoying me because it is a little bit different from other languages.

Ternary operator is a way to say: If this condition, then a, else b“. Most of languages are just using the similar pattern to describe it, but not Python.

Language Ternary Operator
C condition ? a : b
C++ condition ? a : b
JavaScript condition ? a : b
PHP condition ? a : b
ActionScript3 condition ? a : b
Java condition ? a : b
Perl condition ? a : b
Ruby condition ? a : b
Perl 6 condition ?? a !! b
Bash condition && a || b
Python a if condition else b

You know how I feel now.

But in Python, there’s other way to write an elegant ternary operator by using list:

name = "eva"
result = ["This is False", "This is True"][bool(name == "cas")]
print(result) // This is False

Related Articles:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s