Conditional Expressions and Syntax

Conditional Expressions

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)

0 responses to Conditional Expressions and Syntax

Leave a Comment
  1. (required)
  2. Ignore this field:
  3. Don't put anything in this field:
    Don't put anything here:
  4. Leave this empty:
    (required)
  5. Your email is not publically displayed.