Processing Arrays Using the continue Clause


A loop sometimes finishes the task that it’s performing with a particular sequence or array elements, but you want to continue processing with the next element. In this case, you use the continue clause rather than the break clause of the loop. The continue clause will continue with the next loop and bypass the rest of the current loop. Listing 4-10 shows an example of how you can use the continue clause to request specific input from the user.

Listin g 4-10: Using continue to process sequences

[code]# Define a list of keywords.
Keywords = [‘RED’, ‘YELLOW’, ‘BLUE’]
# Define a variable to detect a correct entry.
IsCorrect = False
# Create a loop to query the user about the keyword.
while not IsCorrect:
# Ask the user for the keyword.
Answer = raw_input(‘Type a keyword: ‘).upper()
# Detect a correct keyword.
if Answer in Keywords:
print ‘Congratulations, you provided the keyword!’
IsCorrect = True
# Tell the user the answer is incorrect.
print ‘You provided an incorrect keyword’
# Try again?
Answer = raw_input(‘Continue (Y/N)? ‘).upper()
if Answer == ‘N’:
IsCorrect = True
# Pause after the debug session.
raw_input(‘nPress any key to continue…’)[/code]

The code begins by creating a Keywords array that contains a list of words the application is seeking. It then creates a variable, IsCorrect, to track the correctness of the user input and a while loop to keep asking for input until the user either gives up or provides a correct term.

The next step is to get some input. The example uses raw_input() to obtain the information. Notice the use of upper() to change the case of the input text (so the user can input it without worrying about case sensitivity).

At this point, the code checks the input. If Answer is in Keywords (in other words, if the word in Answer matches one of the words in Keywords), then the loop prints a congratulatory message and loops without processing the rest of the information. Because IsCorrect is now True, the loop ends.

When the user doesn’t provide good input, the loop continues. The code outputs an error response and asks the user about continuing. When the user enters N, the loop ends; otherwise, the loop continues. Figure 4-10 shows example output from this application.

Use continue to resume processing the next element.