9.1 if Statements

In simple terms, the Python if statement selects actions to perform. It's the primary selection tool in Python and represents much of the logic a Python program possesses. It's also our first compound statement; like all compound Python statements, the if may contain other statements, including other ifs. In fact, Python lets you combine statements in a program both sequentially (so that they execute one after another), and arbitrarily nested (so that they execute only under certain conditions).

9.1.1 General Format

The Python if statement is typical of most procedural languages. It takes the form of an if test, followed by one or more optional elif tests (meaning "else if"), and ends with an optional else block. Each test and the else have an associated block of nested statements indented under a header line. When the statement runs, Python executes the block of code associated with the first test that evaluates to true, or the else block if all tests prove false. The general form of an if looks like this:

if <test1>:               # if test      <statements1>         # Associated block elif <test2>:             # Optional elifs      <statements2> else:                     # Optional else     <statements3>

9.1.2 Examples

Let's look at a few simple examples of the if statement at work. All parts are optional except the initial if test and its associated statements; in the simplest case, the other parts are omitted:

>>> if 1: ...     print 'true' ... true

Notice how the prompt changes to " . . . " for continuation lines in the basic interface used here (in IDLE, you'll simply drop down to an indented line instead hit Backspace to back up); a blank line terminates and runs the entire statement. Remember that 1 is Boolean true, so this statement's test always succeeds; to handle a false result, code the else:

>>> if not 1: ...     print 'true' ... else: ...     print 'false' ... false

Now, here's an example of the most complex kind of if statement with all its optional parts present:

>>> x = 'killer rabbit' >>> if x == 'roger': ...     print "how's jessica?" ... elif x == 'bugs': ...     print "what's up doc?" ... else: ...     print 'Run away! Run away!' ... Run away! Run away!

This multiline statement extends from the if line, through the else block. When run, Python executes the statements nested under the first test that is true, or the else part if all tests are false (in this example, they are). In practice, both the elif and else parts may be omitted, and there may be more than one statement nested in each section. Moreover, the words if, elif, and else are associated by the fact that they line up vertically, with the same indentation.

9.1.2.1 Multiway branching

If you've used languages like C or Pascal, you might be interested to know that there is no "switch" or "case" statement in Python that selects an action based on a variable's value. Instead, multiway branching is coded as either a series of if/elif tests as done in the prior example, or by indexing dictionaries or searching lists. Since dictionaries and lists can be built at runtime, they're sometimes more flexible than hardcoded if logic:

>>> choice = 'ham' >>> print {'spam':  1.25,         # A dictionary-based 'switch' ...        'ham':   1.99,         # Use has_key(  ) or get(  ) for default. ...        'eggs':  0.99, ...        'bacon': 1.10}[choice] 1.99

Although it usually takes a few moments for this to sink in the first time you see it, this dictionary is a multiway branch indexing on key choice branches to one of a set of values much like a "switch" in C. An almost equivalent and more verbose Python if statement might look like this:

>>> if choice == 'spam': ...     print 1.25 ... elif choice == 'ham': ...     print 1.99 ... elif choice == 'eggs': ...     print 0.99 ... elif choice == 'bacon': ...     print 1.10 ... else: ...     print 'Bad choice' ... 1.99

Notice the else clause on the if here to handle the default case when no key matches. As we saw in Chapter 6, dictionary defaults can be coded with has_key tests, get method calls, or exception catching. All of the same techniques can be used here to code a default action in a dictionary-based multiway branch. Here's the get scheme at work with defaults:

>>> branch = {'spam': 1.25, ...           'ham':  1.99, ...           'eggs': 0.99} >>> print branch.get('spam', 'Bad choice') 1.25 >>> print branch.get('bacon', 'Bad choice') Bad choice

Dictionaries are good at associating values with keys, but what about more complicated actions you can code in if statements? In Part IV, you'll learn that dictionaries can also contain functions to represent more complex branch actions, and implement general jump tables. Such functions appear as dictionary values, are often coded as lambdas, and are called by adding parenthesis to trigger their action.



Learning Python
Learning Python: Powerful Object-Oriented Programming
ISBN: 0596158068
EAN: 2147483647
Year: 2003
Pages: 253
Authors: Mark Lutz

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net