Combining 2 ternary conditions, how to?

Hi,
newbie, wonderings :slightly_smiling_face:
1: if it is safe to combine 2 (or more) ternary conditions.
as in this way : (e>f) ? “e” : (f<g) ? “f” : “g” - with : e=2, f=4, g=8
?
or if that is not recomended.
Thanks

Don’t see anything wrong with that, if that’s the most readable way to present your code go for it.

1 Like

Ok, so when I’m trying to change the last condition >/<…it always returns me with “g” (never “f”)…
So, how would one writte it so that it also returns f when f<g is true…
testing in jupyter localhost

Sorry I’m not sure I’m following you - the last condition is (f < g) in your post above, and when you change that to (f > g) and you have f = 4, g = 8 then that’s false and hence "g" is returned. What output are you expecting?

2 Likes

Ooops, my bad, the f value was changed = to 8 (f=g)
so that is why (I guess) it was always returning me “g” in both case (f>g) or (f<g)…wich is somehow interesting to know too…

you do not receive an “error/warning” msg if both values are equal, meanwhile you check if one is greater than the other ! it just returns you the last value of the condition I guess…

answer : (e>f) ? e : (f<g) ? “f” : “g” (…and f=4)
f is returned now. which is what I was expecting

I guess that is why they mostly advise us to use “>=” instead of strict “>” !

Why would you expect an error or warning if both values are equal? Doing e.g. 4 < 4 is perfectly legal and unambiguously false. Use <=, >= and == to explicitly handle cases where numbers are equal.

2 Likes

it does sounds logical to me that 4>4 could possibly return a warning…
as for using > instead o >=… as of now, i’m just following this online course : Conditionals | JuliaAcademy

thanks for your time nils ! I guess that is solved by now

I think you’ll struggle to find any programming language where > or < give a warning for equal numbers - it is a pretty unambiguous question (“is number one bigger/smaller than number 2”) with an unambiguous answer. Similarly, you wouldn’t expect 1 < 2 to return something like “it’s still smaller, but pretty close!”

In any case it’s always helpful to consider the documentation, here’s the relevant section: Mathematical Operations and Elementary Functions · The Julia Language

3 Likes