Choosing Which Statements to Execute

An if statement lets you change how your program behaves based on a condition. The general form of an if statement is as follows:

 if​ condition:
  block

The condition is an expression, such as color != “neon green” or x < y. (Note that this doesn’t have to be a Boolean expression. As we discussed in Using Numbers and Strings with Boolean Operators, non-Boolean values are treated as True or False when required.)

As with function bodies, the block of statements inside an if must be indented. As a reminder, the standard indentation for Python is four spaces.

If the condition is true, the statements in the block are executed; otherwise, they are not. As with 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 do something you didn’t intend because some statements were not indented properly. We’ll briefly explore both problems in this chapter.

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


Table 7. Solution Categories

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:

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: ​6.0
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
 ...
 6.0 is acidic.

Recall from Getting Information from the Keyboard, that we have to convert user input from a string to a floating-point number before doing the comparison. Also, here we are providing a prompt for the user by passing a string into function input; Python prints this string to let the user know what information to type.

If the condition is false, the statements in the block aren’t executed:

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: ​8.0
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
 ...
 >>>

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

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: ​6
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
  File "<stdin>", line 2
  print(ph, "is acidic.")
  ^
 IndentationError: expected an indented block

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

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: ​6.0
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
 ...​​ ​​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:

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: ​8.0
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
 ...
 >>>​​ ​​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:

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: ​8.0
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
 ...​​ ​​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:

 ph = 8.0
 if​ ph < 7.0:
 print​(ph, ​"is acidic."​)
 print​(​"You should be careful with that!"​)

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

Of course, sometimes we encounter situations where a single decision isn’t sufficient. If multiple criteria have to be examined, we have 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 (if it’s exactly 7, then it’s neutral and our code won’t print anything):

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: ​8.5
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
 ...
 >>>​​ ​​if​​ ​​ph​​ ​​>​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is basic."​​)
 ...
 8.5 is basic.
 >>>

Here’s a flowchart that shows how Python executes the if statements. The diamonds are conditions, and the arrows indicate what path to take depending on the results of evaluating those conditions:

images/cond/if.png

Notice 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:

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: ​8.5
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
 ...​​ ​​elif​​ ​​ph​​ ​​>​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is basic."​​)
 ...
 8.5 is basic.
 >>>

The difference between the two is that elif is checked only when the if condition above it evaluated to False. Here’s a flowchart for this code:

images/cond/elif.png

This flowchart shows that if the first condition evaluates to True, the second condition is skipped.

If the pH is exactly 7.0, neither clause matches, so nothing is printed:

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: ​7.0
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
 ...​​ ​​elif​​ ​​ph​​ ​​>​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is basic."​​)
 ...
 >>>

With the ph example, we accomplished the same thing with two if statements as we did with an if/elif.

This is not always the case; for example, if the body of the first if changes the value of a variable used in the second condition, they are not equivalent. Here is the version with two ifs:

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: 6.0
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​ph​​ ​​=​​ ​​8.0
 ...
 >>>​​ ​​if​​ ​​ph​​ ​​>​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
 ...
 8.0 is acidic.

And here is the version with an if/elif:

 >>>​​ ​​ph​​ ​​=​​ ​​float(input(​​'Enter the pH level: '​​))
 Enter the pH level: 6.0
 >>>​​ ​​if​​ ​​ph​​ ​​<​​ ​​7.0:
 ...​​ ​​ph​​ ​​=​​ ​​8.0
 >>>​​ ​​elif​​ ​​ph​​ ​​>​​ ​​7.0:
 ...​​ ​​print(ph,​​ ​​"is acidic."​​)
 ...
 >>>

As a rule of thumb, if two conditions are related, use if/elif instead of two ifs.

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

 >>>​​ ​​compound​​ ​​=​​ ​​input(​​'Enter the compound: '​​)
 Enter the compound: ​CH4
 >>>​​ ​​if​​ ​​compound​​ ​​==​​ ​​"H2O"​​:
 ...​​ ​​print(​​"Water"​​)
 ...​​ ​​elif​​ ​​compound​​ ​​==​​ ​​"NH3"​​:
 ...​​ ​​print(​​"Ammonia"​​)
 ...​​ ​​elif​​ ​​compound​​ ​​==​​ ​​"CH4"​​:
 ...​​ ​​print(​​"Methane"​​)
 ...
 Methane
 >>>

As we saw in the ​code​​​, 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:

 >>>​​ ​​compound​​ ​​=​​ ​​input(​​'Enter the compound: '​​)
 Enter the compound: ​H2SO4
 >>>​​ ​​if​​ ​​compound​​ ​​==​​ ​​"H2O"​​:
 ...​​ ​​print(​​"Water"​​)
 ...​​ ​​elif​​ ​​compound​​ ​​==​​ ​​"NH3"​​:
 ...​​ ​​print(​​"Ammonia"​​)
 ...​​ ​​elif​​ ​​compound​​ ​​==​​ ​​"CH4"​​:
 ...​​ ​​print(​​"Methane"​​)
 ...​​ ​​else:
 ...​​ ​​print(​​"Unknown compound"​​)
 ...
 Unknown compound
 >>>

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 else:

 if​ condition:
  if_block
 else​:
  else_block

Logically, that code is the same as this code (except that the condition is evaluated only once in the first form but twice in the second form):

 if​ condition:
  if_block
 if​ ​not​ condition:
  else_block
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.154.252