Most programming languages permit us to execute a block of code when a conditional expression, or if statement, is satisfied. We already saw examples of conditional tests in code like [w for w in sent7 if len(w) < 4]. in the following program, we have created a variable called word containing the string value 'cat'. The if statement checks whether the test len(word) < 5 is true. it is, so the body of the if statement is invoked and the print statement is executed, displaying a message to the user. Remember to indent the print statement by typing four spaces.
When we use the Python interpreter we have to add an extra blank line O in order for it to detect that the nested block is complete.
if we change the conditional test to len(word) >= 5, to check that the length of word is greater than or equal to 5, then the test will no longer be true. This time, the body of the if statement will not be executed, and no message is shown to the user: >>> if len(word) >= 5:
... print 'word length is greater than or equal to 5' >>>
An if statement is known as a control structure because it controls whether the code in the indented block will be run. Another control structure is the for loop. Try the following, and remember to include the colon and the four spaces:
>>> for word in ['Call', 'me', 'Ishmael', '.']: ... print word
This is called a loop because Python executes the code in circular fashion. It starts by performing the assignment word = ' Call', effectively using the word variable to name the first item of the list. Then, it displays the value of word to the user. Next, it goes back to the for statement, and performs the assignment word = 'me' before displaying this new value to the user, and so on. It continues in this fashion until every item of the list has been processed.
Was this article helpful?