Skip to Content
Python: Essential Reference, Third Edition
book

Python: Essential Reference, Third Edition

by David Beazley
February 2006
Intermediate to advanced content levelIntermediate to advanced
648 pages
14h 53m
English
Sams
Content preview from Python: Essential Reference, Third Edition

Conditionals

The if and else statements can perform simple tests. Here’s an 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"

To denote truth values, you ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python: Essential Reference

Python: Essential Reference

David M. Beazley

Publisher Resources

ISBN: 0672328623Purchase book