Page 191 - Beginning Programming with Pyth - John Paul Mueller
P. 191
1. Type the following code into the notebook — pressing Enter after
each line:
Value = input("Type less than 6 characters: ")
LetterNum = 1
for Letter in Value:
print("Letter ", LetterNum, " is ", Letter)
LetterNum+=1
else:
print("The string is blank.")
This example is based on the one found in the “Creating a basic for loop” section, earlier in the chapter. However, when a user presses Enter without typing something, the else clause is executed.
2. Click Run Cell.
Python displays a prompt asking for input.
3. Type Hello and press Enter.
The application lists each character in the string, as shown
previously in Figure 9-2. However, notice that you also see a
statement saying that the string is blank, which seems
counterintuitive. When using an else clause with a for loop, the
else clause always executes. However, if the iterator isn't valid,
then the else clause still executes, so you can use it as an ending
statement for any for loop. See the article at http://python- notes.curiousefficiency.org/en/latest/python_concepts/break_else.h
for additional details.
4. Repeat Steps 2 and 3. However, simply press Enter instead of
entering any sort of text.
You see the alternative message shown in Figure 9-6 that tells you the string is blank.
FIGURE 9-6: The else clause makes it possible to perform tasks based on an empty sequence.
t