+ 4
Please give me some examples of ternary operators
5 Réponses
+ 7
In Python it would be
(code) If (Condition) else (code)
+ 2
Different languages use it in different ways, the ones I do know are python and java. In java it is useful for return statements especially. Lets say you had a variable “isDay” and you wanted to return a sun if it was day and a moon if it was night. To write this you would do
return isDay ? sun : night
if true, do the first option, otherwise the second option. It’s called ternary(3) because theres three parts.
In python its also useful for assigning variables. Using the same scenario as before, you could do something like
sky = sun if isDay else moon
This can also be used for return statments.
+ 2
int age = 26;
String type = age < 18 ? "child":age < 45? "adult" : "old";
java
+ 1
Example:
String result = condition ?
"condition is true" : "condition is false"
is equivalent to:
String result;
if (condition == true){
result = "condition is true"
}
else
{
Result = "Condon is false"
}
0
ternary operator is like if - else
for example:
(1<2)?2:1
this means:
if 1 lesser than 2 return 2 else return 1
and its equivalent to:
if (1 < 2)
{
return 2;
}
else
{
return 1;
}