November 23rd, 2006 posted by Bender Rodríguez
A conditional expression can have one of two values based on a condition. The syntax is condition ? iftrue : iffalse
(condition) ? val1 : val2
If condition is true, the expression has the value of val1, Otherwise it has the value of val2. You can use a conditional expression anywhere you would use a standard expression.
For example,
status = (age >= 18) ? "adult" : "minor"
This statement assigns the value "adult" to the variable status if age is eighteen or greater. Otherwise, it assigns the value "minor" to status.
Conditional expressions are common maniouvres in C based languages like Java, and even JavaScript makes use of them. Python lacked this ternary operator until 2.5, which works a little differently than the standard C format.
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"
but not by much. That's Python for you.
0 Comments, 0 trackbacks (Trackback URL)"The people who burned witches at the stake never for one moment thought of their act as violence; rather they thought of it as an act of divinely mandated righteousness. The same can be said of most of the violence we humans have ever committed."
Gil Bailie