On Wed, 12 Oct 2005 02:15:40 -0400, Chris Smith <[EMAIL PROTECTED]> wrote:
>>>>>> "Sebastian" == Sebastian Bassi <[EMAIL PROTECTED]> writes: > > Sebastian> On 9/30/05, Reinhold Birkenfeld <[EMAIL PROTECTED]> wrote: > >> after Guido's pronouncement yesterday, in one of the next > >> versions of Python there will be a conditional expression with > >> the following syntax: X if C else Y > > Sebastian> I don't understand why there is a new expression, if > Sebastian> this could be accomplished with: > > Sebastian> if C: X else: Y > > Sebastian> What is the advantage with the new expression? > >One very frequent use case is building a string. But what you show doesn't require choice of which to _evaluate_, since you are merely choosing between immutable constants, and there is no side effect or computation overhead to avoid by not evaluating the unselected expression. So "the answer is " + ('no', 'yes')[X==0] would do as well. >Instead of: > >if X==0: > filler="yes" >else: > filler="no" >return "the answer is %s" % filler > > >What I really want to do is take four lines of conditional, and put >them into one, as well as blow off dealing with a 'filler' variable: > >return "the answer is " + "yes" if X==0 else "no" As has been pointed out, though legal there is some doubt as to whether you meant what you wrote ;-) > > >Or whatever the final release syntax is. >Conditional expressions are a nice way to shim something in place, on >an acute basis. Chronic use of them could lead to a full-on plate of >spaghetti, where you really wanted code. >They can be impenitrable. Whenever I'm dealing with them in C/C++, I >always line the ?, the :, and the ; characters vertically, which may >seem a bit excessive in terms of whitespace, but provides a nice >hieroglyph over on the right side of the screen, to make things >obvious. >Best, >Chris Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list