2.1.3 Decision structures
Many scripts that you write will need to have conditional logic that executes a block of code given a condition and perhaps executes a different block of code given a different condition. The "if." "elif," and "else" statements in Python provide this conditional logic. Try typing this example in the PythonWin Interactive Window:
>>> x = 3 >>> if x > 2: ... print "Greater than two" ... Greater than two
In the above example, the keyword "if" denotes that some conditional test is about to follow. In this case, the condition of x being greater than two was met, so the script printed "Greater than two." Notice that you are required to put a colon (:) after the condition and indent any code executing because of the condition. For consistency in this class, all indentation is done using four spaces.
Using "else" is a way to run code if the condition isn't met. Try this:
>>> x = 1 >>> if x > 2: ... print "Greater than two" ... else: ... print "Less than or equal to two" ... Less than or equal to two
Notice that you don't have to put any condition after "else." It's a way of catching all other cases. Again the conditional code is indented four spaces, which makes the code very easy for a human to scan. The indentation is required because Python doesn't require any type of "end if" statement (like many other languages) to denote the end of the code you want to execute.
If you want to run through multiple conditions, you can use "elif", which Python's abbreviation for "else if":
>>>x = 2 >>> if x > 2: ... print "Greater than two" ... elif x == 2: ... print "Equal to two" ... else: ... print "Less than two" ... Equal to two
In the code above, "elif x == 2:" tests whether x is equal to two. The == is a way to test whether two values are equal. Using a single = in this case would result in an error because = is used to assign values to variables. In the code above, you're not trying to assign x the value of 2, you want to check if x is already equal to 2, hence you use ==.
Caution: Using = instead of == to check for equivalency is a very common Python mistake, especially if you've used other languages where = is allowed for equivalency checks.
You can also use if, elif, and else to handle multiple possibilities in a set. The code below picks a random school from a list (notice we had to import the random module to do this and call a special method random.randrange()). After the school is selected and its name is printed, a series of if/elif/else statements appears that handles each possibility. Notice that the else statement is left in as an error handler; you should not run into that line if your code works properly, but you can leave the line in there to fail gracefully if something goes wrong.
import random # Choose a random school from a list and print it schools = ["Penn State", "Michigan", "Ohio State", "Indiana"] randomSchoolIndex = random.randrange(0,4) chosenSchool = schools[randomSchoolIndex] print chosenSchool # Depending on the school, print the mascot if chosenSchool == "Penn State": print "You're a Nittany Lion" elif chosenSchool == "Michigan": print "You're a Wolverine" elif chosenSchool == "Ohio State": print "You're a Buckeye" elif chosenSchool == "Indiana": print "You're a Hoosier" else: print "This program has an error"
Some other programming languages have special keywords for doing the above, such as switch or select case. In Python, however, it's usually just done with a long list of "if"s and "elif"s.