Ternary Operator
Unary operator are ones that operate on one stuff like the tilde ~ operator, you can do something like ~ a, ~ false etc and get a result. Binary operators operators act on two stuff, like the plus + operator. You can do 1 + 2 and so on, they get 2 operands. Ternary operator, operates on three stuffs. Take a look at the program below:
a = 10; b = 15
max = b > a ? b : a
min = b < a ? b : a
println("Maximum = ", max)
println("Minimum = ", min)
Output:
Maximum = 15
Minimum = 10
Type it in your Jupyter lab and execute it. So this program is able to find maximum and minimum of two values. Let’s see how it works.
First we assign a to 10 and b to 15 here:
a = 10; b = 15
Next look at this line:
max = b > a ? b : a
Here we have a variable max and we are assigning something to it with an equal to = operator. The interesting part is at the right side, look at it carefully, it goes like this b > a ? b : a. Note the syntax here. There is a condition b > a, so it becomes true or false depending on the avlues of b and a, at the right of it is a ? b : a. If b > a is true, the the stuff between question ? and : get returned and b is assigned to max. If b > a is false, the stuff after the : is assigned to max that is a.
So this ternary operator ? : deals with three stuffs.
- A condition
<condition> ? : - Something to be returned or done when the condition is
true<condition> ? <do something when true> : - Something to be returned or done when the condition is
false<condition> ? <do something when true> : <do something when false>.
I think you can figure out rest of the program by yourself.
As an exercise why don’t you write a simple program with uses ternary operator and and does this:
- It multiplies two variables
aandbwhen a variable namedactionis set tomultiply - It adds two variables
aandbwhen a variable namedactionis set to any other value - Finally it prints out the result
The Jupyer notebook for this blog is available here https://gitlab.com/data-science-with-julia/code/-/blob/master/ternary_operator.ipynb.