Ternary Operator and Other Shorthand Code

The ternary operator is a shorthand way of writing an if/else statement where a particular action occurs in both cases, but the value associated with that action depends on the condition stated.

For example, the traditional if/else construct (C/Java/JavScript syntax):

if (a > b) {
   result = x;
else {
   result = y;

can be rewitten as:

This in itself is a huge benefit to clean, concise code. I use it wherever possible. Here’s an example in PHP:

A particularly cool Python example utilising the idea of a function of a comprehended list:

If you want to return/echo true or false depending on the condition, there is no need for the ternary operator as a shorter operator is available: simply echo the boolean result of the condition, i.e. rather than:

This will produce the same output:

There are various other implementations of this idea in different languages, but the reason for this blog post is because while talking about these with my colleague Mike and I came up with an interesting manipulation of this on the train to work the other day. I had a program which incremented a value by 1 if and only if a condition was true:

In my opinion this is good because it’s on one line, but bad because the else 0 should be unnecessary. Unfortunately Python requires an else here. The obvious alternative doesn’t use a +0 but requires 2 lines:

Anyway, the thing we thought of was to increment by the integer value of the boolean, i.e. 1 if True, 0 if False:

Evaluating a condition, say x>0, returns True or False, which when added to an integer is equal to 1. Another implementation of this is to multiply the value of the condition by a scaling factor:

Published by

Ben Nuttall

Raspberry Pi Community Manager. Into free software, maths, kayaking, GitHub, Adventure Time & Futurama. @ben_nutall on Twitter