4.1. If-then construction (Conditionals)¶
Here is an example of the
if-then construction in Python:
results,unknown_words = set(), set() if item in vocabulary: results.add(item)
This piece of code runs a test. The test is:
>>> item in vocabulary True
That is, we are checking to see if the value of the variable
(most likely a string) is in some container called
This test is an expression that has a value just like other Python
expressions. The value is going to be either
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.
item is in
vocabulary, we add it to
a container called
(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:
results,unknown_words = set(), set() if item in vocabulary: results.add(item) else: unknown_words.add(item)
In this case, if
item is in
we add it to
item is not in
we record it in a container called
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
if item in vocabulary: results.add(item) elif item.istitle(): pass else: unknown_words.add(item)
Recall from Strings that the method
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.”