print( ["even", "odd"][num % 2] )
If you need to avoid evaluating the wrong branch:
print( [lambda: "even", lambda: "odd"][num % 2]() )
Cursed
Not as cursed as
print("eovdedn"[n%2::2])
For optimal performance, you should rewrite it in Rust:
inline_python::python! { print(js2py.eval_js("(number) => number % 2 ? 'odd' : 'even'")(number)) };
And now you can use wasm to run it in a browser!
print("odd" if num % 2 else "even")
That’s the native python version, for those curious
The ternary syntax is really my only real gripe with python design – putting the conditional BETWEEN the true and false values feels so very messy to me.
At least you guys have ternary syntax cries in kotlin.
in Scala, everything is an expression, including “if”, maybe kotlin is the same?
Eh, reads pretty naturally to me. That said,
(like I lisp)
Lisps makes more sense to me though
(if condition a b)
VS
a if condition else b
Oh, (you) (really) (like) (Lisp)? (That’s) (great!)
It’s kinda natural to me having used Perl a lot.
That’s not quite the argument you might think it is
Argument?
You know, the stuff in @_
You clearly haven’t used Perl a lot. Perl’s ternary looks like:
$even = $num % 2 ? “nay” : “yay”;
Incidentally, it is also the same as PHP’s, but mainly because PHP stole it.
You do get the if in the middle of stuff though in the form print(debug message) if $debug
Wait until you learn that postfix conditionals are syntactic sugar and the compiler* turns that line into the equivalent of
$debug and print(debug message)
, putting the conditional in first place, a lot like the ternary operator.* Perl compiles to bytecode before running.
The ternary operator itself isn’t implemented in terms of
and
(andor
) but it could be.
Why is the return first?
Please. That’s C’s ternary operator. JS is just a pile of garbage cosplaying as a programming language
Why do you say it’s a pile of garbage?
Because of all the garbage
Clearly the garbage collector is too effective
No they’re not supposed to be piling it up
Is a garbage collector not a garbage disposal. Smh.
One example that’s giving you problems? Maybe even on a daily basis if you use it for work? What’s garbage about it?
num % 2
isn’t a boolean result in any of these languages, so I feel like it would always output “odd”Edit: 0 is false, everything else is true.
0 is false in C, Python, and JS. It should work