4 ms·
Someone else mentioned the fact that default_result if condition else alternate_result is pythons form of ternary expression and semantically equivalent o
by rat87 12y ago
Someone else mentioned the fact that
default_result if condition else alternate_result
is pythons form of ternary expression and semantically equivalent other then pythons truthiness boolean testing of objects(empty collections, 0, empty strings, False, None, 0 timedelta evaluate to False, also objects where obj.__nonzero__() returns False (in python3 __nonzero__ is renamed to __bool__)).
I'd like to bring up that while it's a matter of opinion the older ugly ?: syntax is much less readable even when you memorize it. I never use ?: syntax ternary expressions in languages that have them because I always have to look it up. That's why a number of languages prefer python-like versions or forms which emphasize to an even larger degree the fact that its just an if-else as an expression to an even larger degree(so I'd question that it's standard, I'm not 100% it's older either as I think the LISP version is closer to the python version).
CoffeeScript
s = if condition then "yup" else "nope"
Smalltalk
abs := x > 0 ifTrue: [ x ] ifFalse: [ x negated ]
Ruby has both versions
Scala
a = if (n == 12) "twelve" else "not twelve"
Rust
let y = if x == 5 { 10 } else { 15 }; // y: i32
Haskell
fac x = if x==0 then
1
else x * fac (x - 1)
(some examples taken from http://rosettacode.org http://rosettacode.org)
- SilasX 12y agoWhen first learning python (Shaw's The Hard Way maybe), it suggested this idiom as python's ternary operator: boolean and true_branch or false_branch and explained that boolean=true would make it check and return true_branch, while false makes it check the other side of the or. This is parallel to the standard C one. I'm surprised no one has mentioned it, but I guess that makes sense because it's not very explicit about what it's doing, which goes agains the spirit of python. Probably not very common for python programmers to use.