The ternary operator is a way to concisely say:
“If test, then a, else b“,
with the value of the statement being the value of a or b.
language | how to say it |
---|---|
C | test ? a : b |
C++ | test ? a : b |
javascript | test ? a : b |
Perl (not perl 6) | test ? a : b |
PHP | test ? a : b |
Ruby | test ? a : b |
Did I forget some language? | probably |
Python | a if test else b (Why??) |
Why??
Ok. Now that I’ve written this post, I’ll remember it.
However, I just want to say…
On behalf of all of the other multiple-language programmers in the world, …
THIS IS LAME!!!
No really, why??
Well, there are some reasonable reasons.
The Python version is more readable (at least in English).
And, to tell you the truth, if I ONLY were programming in Python, I’d probably prefer the Python version.
However, I don’t. I spend quite a bit of time in C++, Perl, PHP, and javaScript. And they ALL use the other form!
I understand the reasoning behind Python’s version.
I JUST DON’T AGREE WITH IT!
Rant over
Glad I’ve gotten that off my chest.
As of July, 2025, I mostly use Python, although from college and early career through like 8 months ago, I wrote a lot of C/C++.
And as of 2025, I still wish Python had the ternary operator that the rest in the list have.
However, since I wrote this post so many years ago, I have rememberd the difference. So it’s worked. :)