If Statements

The basic form of an if statement is as follows:

if condition: block

The condition is an expression, such as name != " or x < y. Note that this doesn't have to be a Boolean expression. As we discussed in Section 6.1, Applying Boolean Operators to Integers, Floats, and Strings, on page 114, non-Boolean values are automatically converted to True or False when required.

In particular, 0, None, the empty string ", and the empty list [] all are considered to false, while all other values that we have encountered are considered to be true.

If the condition is true, then the statements in the block are executed; otherwise, they are not. As with loops and functions, the block of statements must be indented to show that it belongs to the if statement. If you don't indent properly, Python might raise an error, or worse, might happily execute the code that you wrote but, because some statements were not indented properly, do something you didn't intend. We'll briefly explore both problems in this chapter.

Here is a table of solution categories based on pH level:

pH Level Solution Category

0-4 Strong acid

5-6 Weak acid

7 Neutral

8-9 Weak base

10-14 Strong base

We can use an if statement to print a message only when the pH level given by the program's user is acidic:

Download cond/if_basictrue.cmd

... print "%s is acidic." % (ph) 6.0 is acidic.

(Recall from Section 3.6, User Input, on page 46 that we have to convert user input from a string to a float before doing the comparison.)

If the condition is false, the statements in the block are not executed:

Download cond/if_basicfalse.cmd

If we don't indent the block, Python lets us know:

Download cond/if_indenterror.cmd

... print "%s is acidic." % (ph) File "<stdin>", line 2

IndentationError: expected an indented block

Since we're using a block, we can have multiple statements, which are executed only if the condition is true:

Download cond/if_multilinetrue.cmd

... print "You should be careful with that!"

6.0 is acidic.

You should be careful with that!

When we indent the first line of the block, the Python interpreter changes its prompt to ... until the end of the block, which is signaled by a blank line:

Download cond/if_multiline_indent_error.cmd

>>> print "You should be careful with that!" You should be careful with that!

If we don't indent the code that's in the block, the interpreter complains:

Download cond/if_multiline_indent_error2.cmd

... print "%s is acidic." % (ph) ... print "You should be careful with that!" File "<stdin>", line 3

print "You should be careful with that!"

SyntaxError: invalid syntax

If the program is in a file, then no blank line is needed. As soon as the indentation ends, Python assumes that the block has ended as well. This is therefore legal:

Download cond/if_multiline_indent_error3.cmd

print "%s is acidic." % (ph) print "You should be careful with that!"

In practice, this slight inconsistency is never a problem, and most people never even notice it.

Of course, sometimes there are situations where a single decision isn't sufficient. If there are multiple criteria to examine, there are a couple of ways to handle it. One way is to use multiple if statements. For example, we might print different messages depending on whether a pH level is acidic or basic:

Download cond/multi_if.cmd

... print "%s is acidic." % (ph) >>> if ph > 7.0:

In Figure 6.4, on the following page, we see that both conditions are always evaluated, even though we know that only one of the blocks can be executed. We can merge both cases by adding another condition/block pair using the elif keyword (which stands for "else if"); each condition/block pair is called a clause:

Download cond/elif_basic.cmd

Figure 6.4: if statement

The difference between the two is that the elif is checked only when the if above it was false. In Figure 6.5, on the next page, we can see the difference pictorially, with conditions drawn as diamonds, other statements as rectangles, and arrows to show the flow of control.

An if statement can be followed by multiple elif clauses. This longer example translates a chemical formula into English:

Download cond/elifjonger.cmd

>>> if compound == "H2O": ... print "Water" ... elif compound == "NH3": ... print "Ammonia" ... elif compound == "CH3": ... print "Methane"

Methane

Figure 6.5: elif statement

If none of the conditions in a chain of if/elif statements are satisfied, Python does not execute any of the associated blocks. This isn't always what we'd like, though. In our translation example, we probably want our program to print something even if it doesn't recognize the compound. To do this, we add an else clause at the end of the chain:

Download cond/else_basic.cmd

>>> if compound == "H2O": ... print "Water" ... elif compound == "NHS": ... print "Ammonia" ... elif compound == "CHS": ... print "Methane" ... else:

... print "Unknown compound"

Unknown compound >>>

if Statements M 124

An if statement can have at most one else clause, and it has to be the final clause in the statement. Notice there is no condition associated with the else; logically, the following statement:

if condition: if-block else:

else-block is the same as this:

if condition: if-block if not condition: else-block

Was this article helpful?

0 0

Post a comment