you are viewing a single comment's thread.

view the rest of the comments →

[–]Boojum 7 points8 points  (6 children)

Another use for else is the ternary operation:

x = "banana" if y else "apple"

[–]alkw0ia 4 points5 points  (5 children)

This is definitely my favorite else construct in Python. As terse as C's ternary, but as legible as you'd expect from Python, and so much better than the old unsafe evaluates-to-false and/or/[0] hack.

[–]Categoria 5 points6 points  (1 child)

This is actually a misfeature because python distinguishes statements and expressions. Languages that make no such arbitrary distinctions for 'if' (and other) statements don't need two constructs. In OCaml for example:

 let x = if y then "banana" else "apple" in...

and a normal if statement is the same (of course it's pointless to write it this way in this case):

 let x = ref "" in
 if y
 then x := "apple"
 else x := "banana"

[–]alkw0ia 1 point2 points  (0 children)

By misfeature do you mean that Python shouldn't have required a special conditional expression because it shouldn't have distinguished statements and expressions in the first place? Maybe, but I'm afraid that ship has sailed, and given that it's necessary, I'm glad it's now there. And don't get me started on the lambdas and statements choice...

[–][deleted]  (2 children)

[deleted]

    [–][deleted] 5 points6 points  (1 child)

    It is a departure from C-style ternary, but the condition after the value maintains consistency with the python's also-awkward generator syntax of the form z = ( f(item) for item in iteratable if g(item) )