Monday, March 01, 2010

Truth and Python 3: The if statement

In it's basic form the Python if statement looks like this:

if expression:
    statements

If expression is true, statements are executed; otherwise statements are skipped. expression can be of any type; it doesn't have to evaluate to True or False. The if statement automatically converts expression to bool(expression) if needed.

Unlike other languages, parenthesis are not required around expression. In fact, it's considered bad style to include them.

If statements consists of a single statement, the whole if statement may be written as one line:

if expression: statement

The else Clause

The if statement can include an else clause. The else clause is optional; an if statement doesn't have to have one.

if expression:
    statements
else:
    else-statements

The else-statements are executed if none of the other branches of the if statement are executed. In the case above, if expression is false, else-statements are executed.

The elif Clauses

The if statement can include one or more elif or 'else-if' clauses. These clauses are also optional.

if expression:
    statements
elif elif-1-expression:
    elif-1-statements
elif elif-2-expression:
    elif-2-statements
more elif clauses...

An elif clause contains an expression and statements. The elif statements are only examined if expression is false. The interpretter starts going through the elif conditions from top to bottom until it finds one that is true. It then executes the corresponding statements and exits the if statement.

The if Statement in Full

An if statement may include both elif clauses and an else clause. The complete form of the if statement looks like this:

if expression:
    statements
elif elif-1-expression:
    elif-1-statements
elif elif-2-expression:
    elif-2-statements
more elif clauses...
else:
    else-statement