Using the if-elif-else Structure


Using the if-elif-else Structure

Choosing from among several possibilities is the job of the if-elif-else structure. It's the most powerful and flexible of all the conditional structures. It can be used in multiple ways, but comes in quite handy when you have one variable that you want to compare to a bunch of different values.

Introducing the Mood Computer Program

In the mid-1970s (yes, last century), there was a wildly successful, fad product called the Mood Ring. The ring revealed the wearer's mood through a color-changing gem. Well, the Mood Computer program takes the technology to the next level by looking into the psyche of the user and displaying his or her mood. Figure 3.7 reveals my mood while writing this very chapter.

click to expand
Figure 3.7: Looks like I was in a great mood while writing the Mood Computer program.

Okay, the program doesn't really plum the emotional depths of the user through electrodermal impulses transmitted via the keyboard. Instead, Mood Computer generates a random number to choose one of three faces to print through an if-elif-else structure. By the way, the Mood Ring didn't really reveal the wearer's emotions either. It was just an LCD that changed colors based on body temperature.

The program code for Mood Computer:

 # Mood Computer # Demonstrates the if-elif-else structure # Michael Dawson - 12/29/02 import random print "I sense your energy. Your true emotions are coming across my screen." print "You are..." mood = random.randrange(3) if mood == 0:     # happy     print \     """        -----------        |         |        | O     O |        |    <    |        |         |        | .    . |        |  `...`  |        -----------                     """ elif mood == 1:     # neutral     print \     """        -----------        |         |        | O     O |        |    <    |        |         |        | ------- |        |         |        -----------                     """ elif mood == 2:     # sad     print \     """        -----------        |         |        | O     O |        |    <    |        |         |        |  .'.   |        | '   '   |        -----------                      """ else:        print "Illegal mood value! (You must be in a really bad mood)." print "...today." raw_input("\n\nPress the enter key to exit.") 

Examining the if-elif-else Structure

An if-elif-else structure can contain a whole list of conditions for a program to evaluate. In Mood Computer, the lines containing the different conditions are

  • if mood == 0:

  • elif mood == 1:

  • elif mood == 2:

Notice that you write the first condition using an if clause, but then list the remaining conditions using elif (short for "else if") clauses. elif clauses are constructed just like if clauses. And you can have as many elif clauses as you like.

HINT

Although the if-elif-else structure is flexible enough to test a list of unrelated conditions, it's almost always used to test related ones.

By isolating the conditions, you can see the purpose of the structure: to test mood against three different values. The program first checks to see if mood is equal to 0. If it is, then the happy face is printed. If not, the program moves to the next condition and checks if mood is equal to 1. If it is, the neutral face is printed. If not, the program checks if mood is equal to 2. If so, the sad face is printed.

TRAP

An important feature of the if-elif-else structure is that once a condition evaluates to true, the computer executes its corresponding block and exits the structure. This means that at most, only one block executes, even if several conditions are true. In Mood Computer, that's no big deal. mood can only be equal to a single number, so only one of the conditions can be true. But it's important to be aware of this behavior because it's possible to create structures where more than one condition can be true at the same time. In that case, only the block associated with the first true condition executes.

If none of the preceding conditions for mood turn out to be true, then the final else clause's block runs and Illegal mood value! (You must be in a really bad mood). appears on the screen. This should never happen, since mood will always be either 0, 1, or 2. But I put the clause in there just in case. I didn't have to, though, since the final else clause is optional.

HINT

Even though it's not necessary to use the final else clause, it's a good idea. It works as a catchall for when none of the conditions are true. Even if you think one of your conditions will always be true, you can still use it to catch the "impossible" case, like I did.

You've seen three similar, but progressively more powerful branching structures. For a concise review, check out Table 3.2.

Table 3.2: B RANCHING STRUCTURES SUMMARY

Structure

Description

 if <condition>:   <block> 

if structure. If <condition> is true, <block> is executed; otherwise it's skipped.

 if <condition>:   <block 1> else:   <block 2> 

if-else structure. If <condition> is true, <block1> is executed; otherwise <block2> is executed.

 if <condition 1>:   <block 1> elif <condition 2>:   <block 2>       .       .       . .elif <condition N>:   <block N> else:   <block N+1> 

if-elif-else structure. The block of the first true condition is executed. If no condition is true, the optional else clause's block, <block N+1>, is executed.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

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