4.1. If-then construction (Conditionals)ΒΆ

Here is an example of the if-then construction in Python:

if item in vocabulary:
   results.add(item)

This piece of code runs a test. The test is:

item in vocabulary

That is, we are checking to see if the value of the variable item (most likely a string) is in some container called vocabulary This test is an expression that has a value just like other Python expressions. The value is going to be either True or False.

What the if-then construction does is pretty intuitive. If the value of the test is True, the indented line of code under the test is run. If the value is False, it is not. So if item is in vocabulary, we add it to a container called results (more on this container in the next section). The basic idea: The second line is run if the condition in the first line is met. Hence, such constructions are often called conditionals.

Here are some variants, which should look quite familiar to anyone with experience with another programming language:

if item in vocabulary:
   results.add(item)
else:
   unknown_words.add(item)

In this case, if item is in vocabulary, we add it to results. if item is not in vocabulary, we record it in a container called unknown_items.

Finally, we might have more than two possibilities to sort through. In this case, we need to have more than one test. For that we use elif:

if item in vocabulary:
   results.add(item)
elif item.istitle():
   pass
else:
   unknown_words.add(item)

Recall from Strings that the method istitle checks for title case, that is, it checks to see if all the words in a string begin with a capitalized word. This might be our test to see if item is a proper name; in that case, we might not want to add it to the unknown words list. As a way of avoiding that, we check to see if item is in titlecase; if it is, we execute the pass command. The pass command does nothing; it’s there because Python requires a line of code after each test, specifying what to do if the test is passed. So Python provides a way to say “Do nothing.”