Python has always been described as a "tight" language in that new syntaxes are only added with a great deal of thought, and then only if they provide a significant benefit without diluting the crispness of the language.
There have been long discussions in the Python world about adding in a conditional operator - something that gives and easier form to an if / else construct that's used only to set a variable to one of two alternative values. Now, in
release 2.5 which went out to Beta release in the last few days, such a facility has been added.
Suppose you have a variable called
stock_level and you want to set up another variable (for output) with the word "is" or "are" in it, depending on whether the stock level is 1 or something else, you can write (as from Python 2.5):
word = "is" if stock_level == 1 else "are"
which is much shorter that the alternative so far available:
if stock_level == 1:
word = "is"
else:
word = "are"
For anyone with a Perl, PHP, C or Java backgrond, this new syntax is the moral equivalent of the ? : operator. After long discussion, Guido van Rossum decided for the syntax shown above ... amongst the reasons for this surprising choice are the fact that the ":" character is already very significant in Python and although the syntax rules would have allowed Python to follow the other languages, resultant code would not have been clear and easy to follow. (written 2006-07-01 07:39:27)
Associated topics are indexed under
Y103 - Python - Conditionals and Loops [1696] Saying NOT in Perl, PHP, Python, Lua ... - (2008-07-04)
[1661] Equality, sameness and identity - Python - (2008-05-31)
[1477] Decisions - small ones, or big ones? - (2007-12-18)
[1201] No switch in Python - (2007-05-23)
[909] Python is like a narrowboat - (2006-10-30)
[835] Python - when to use the in operator - (2006-08-16)
[668] Python - block insets help with documentation - (2006-04-04)
[657] The ternary operator in Python - (2006-03-25)
[353] Wimbledon Neck - (2005-06-20)
[299] What - no switch or case statement? - (2005-05-03)
Some other Articles
Is Java the right language to learn?Strange housewarmingShadow Transport Minister to visit MelkshamHot answers in PHPNew - Conditional expressions in Python 2.5Tk - laying out your GUI with frames, pack and gridFirst Light, Bootle Docks, LiverpoolRunning external processes in Tcl and Tcl/TkWhich way to turn?Good follow up ... my thanks