Linux/Unix > Python Essential Reference, Second Edition > 1. A Tutorial Introduction > Conditionals | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137110163131205251112200021

### Conditionals

The `if` and `else` statements can perform simple tests. For example:

    # Compute the maximum (z) of a and b
    if a < b:
            z = b
    else:
            z = a

The bodies of the `if` and `else` clauses are denoted by indentation. The `else` clause is optional.

To create an empty clause, use the `pass` statement as follows:

    if a < b:
            pass      # Do nothing
    else:
            z = a

You can form Boolean expressions by using the `or`, `and`, and `not` keywords:

    if b >= a and b <= c:
            print "b is between a and c"
    if not (b < a or b > c):
            print "b is still between a and c"

To handle multiple-test cases, use the `elif` statement, like this:

    if a == '+':
            op = PLUS
    elif a == '-':
            op = MINUS
    elif a == '*':
            op = MULTIPLY
    else:
            raise RuntimeError, "Unknown operator"

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.