Skip to content

Processing Data Using the for Statement

Processing Data Using the for Statement

The first looping code block that most developers encounter is the for state- ment. It’s hard to imagine creating a conventional programming language  that lacks such a statement. In this case, the loop executes a fixed number of times, and you know the number of times it will execute before the loop even begins. Because everything about a for loop is known at the outset, for loops tend to be the easiest kind of loop to use. However, in order to use one, you need to know how many times to execute the loop. The following sec- tions describe the for loop in greater detail.

 

 

Understanding the for statement

A for loop begins with a for statement. The for statement describes how  to perform the loop. The Python for loop works through a sequence of some type. It doesn’t matter whether the sequence is a series of letters in a string or items within a collection. You can even specify a range of values to use by specifying the range() function. Here’s a simple for statement.

 

 

The statement begins with the keyword for. The next item is a variable that holds a single element of a sequence. In this case, the variable name is Letter. The in keyword tells Python that the sequence comes next. In this case, the sequence is the string “Howdy”. The for statement always ends with a colon, just as the decision-making statements described in Chapter 7 do.

 

Indented under the for statement are the tasks you want performed within the for loop. Python considers every following indented statement part of the code block that composes the for loop. Again, the for loop works just like the decision-making statements in Chapter 7.

 

 

Creating a basic for loop

The best way to see how a for loop actually works is to create one. In this case, the example uses a string for the sequence. The for loop processes each of the characters in the string in turn until it runs out of characters. This example also appears with the downloadable source code as SimpleFor.py.

 

  1. Open a Python File window.

You see an editor in which you can type the example code.

2y.peT the following code into the window — pressing Enter after each line:

 

The example begins by creating a variable, LetterNum, to track the number of letters that have been processed. Every time the loop com- pletes, LetterNum is updated by 1.

The for statement works through the sequence of letters in the string “Howdy!”. It places each letter, in turn, in Letter. The code that fol- lows displays the current LetterNum value and its associated character found in Letter.

  1. Choose RunRun

A Python Shell window opens. The application displays the letter sequence along with the letter number, as shown in Figure 8-1.

 

 

 

 

 

 

Figure 8-1: Use the for loop to process the characters in a string one at a

time.

 

 

 

Controlling execution with the break statement

Life is often about exceptions to the rule. For example, you might want   an assembly line to produce a number of clocks. However, at some point, the assembly line runs out of a needed part. If the part isn’t available, the assembly line must stop in the middle of the processing cycle. The count hasn’t completed, but the line must be stopped anyway until the missing part is restocked.

 

Interruptions also occur in computers. You might be streaming data from an online source when a network glitch occurs and breaks the connection; the stream temporarily runs dry, so the application runs out of things to do even though the set number of tasks isn’t completed.

 

The break clause makes breaking out of a loop possible. However, you don’t simply place the break clause in your code — you surround it with an if statement that defines the condition for issuing a break. The statement might say something like this: If the stream runs dry, then break out of the loop.

 

In this example, you see what happens when the count reaches a certain level when processing a string. The example is a little contrived in the interest of keeping things simple, but it reflects what could happen in the real world when a data element is too long to process (possibly indicating an error con- dition). This example also appears with the downloadable source code as ForBreak.py.

 

  1. Open a Python File

You see an editor where you can type the example code.

2y.peT the following code into the window — pressing Enter after each line:

 

 

 

This example builds on the one found in the previous section. However, it lets the user provide a variable-length string. When the string is longer than six characters, the application stops processing it.

The if statement contains the conditional code. When LetterNum is greater than 6, it means that the string is too long. Notice the second level of indentation used for the if statement. In this case, the user sees an error message stating that the string is too long, and then the code executes a break to end the loop.

  1. Choose RunRun

You see a Python Shell window open with a prompt asking for input.

  1. Type Hello and press Enter.

The application lists each character in the string, as shown in Figure 8-2.

5fo.rPmerSteps 3 and 4 again, but type               I am too long. instead of Hello.

The application displays the expected error message and stops process- ing the string at character 6, as shown in Figure 8-3.

 

 

 

 

 

 

 

Figure 8-2:

A short string is successfully processed

by the application.

 

 

This example adds length checking to your repertoire of application data error checks. Chapter 7 shows how to perform range checks, which ensure that a value meets specific limits. The length check is necessary to ensure that data, especially strings, aren’t going to overrun the size of data fields. In addition,

a small input size makes it harder for intruders to perform certain types of hacks on your system, which makes your system more secure.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 8-3: Long strings are trun­ cated to ensure that they remain a certain

size.

 

 

Controlling execution with the continue statement

Sometimes you want to check every element in a sequence, but don’t want to process certain elements. For example, you might decide that you want  to process all the information for every car in a database except brown cars.

Perhaps you simply don’t need the information about that particular color of car. The break clause simply ends the loop, so you can’t use it in this situa- tion. Otherwise, you won’t see the remaining elements in the sequence.

 

The break clause alternative that many developers use is the continue clause. As with the break clause, the continue clause appears as part of an if statement. However, processing continues with the next element in the sequence rather than ending completely.

 

 

The following steps help you see how the continue clause differs from the break clause. In this case, the code refuses to process the letter w, but will process every other letter in the alphabet. This example also appears with the downloadable source code as ForContinue.py.

 

  1. Open a Python File window.

You see an editor in which you can type the example code.

2y.peT the following code into the window — pressing Enter after each line:

 

This example is based on the one found in the “Creating a basic for loop” section, earlier in this chapter. However, this example adds an if statement with the continue clause in the if code block. Notice the print() function that is part of the if code block. You never see this string printed because the current loop iteration ends immediately.

  1. Choose RunRun

You see a Python Shell window open. The application displays the letter sequence along with the letter number, as shown in Figure 8-4. However, notice the effect of the continue clause — the letter w isn’t processed.

 

 

 

 

Controlling execution with the pass clause

The Python language includes something not commonly found in other lan- guages: a second sort of continue clause. The pass clause works almost the same way as the continue clause does, except that it allows completion of the code in the if code block in which it appears. The following steps use an example that is precisely the same as the one found in the previous sec- tion, “Controlling execution with the continue statement,” except that it uses a pass clause instead. This example also appears with the downloadable source code as ForPass.py.

 

  1. Open a Python File

You see an editor in which you can type the example code.

2y.peT the following code into the window — pressing Enter after each line:

 

  1. Choose RunRun Module.

You see a Python Shell window open. The application displays the letter sequence along with the letter number, as shown in Figure 8-5. However, notice the effect of the pass clause — the letter w isn’t processed. In addition, the example displays the string that wasn’t displayed for the continue clause example.

 

The continue clause makes it possible to silently bypass specific elements  in a sequence and to avoid executing any additional code for that element. Use the pass clause when you need to perform some sort of post process-   ing on the element, such as logging the element in an error log, displaying a message to the user, or handling the problem element in some other way. The continue and pass clauses both do the same thing, but they’re used in dis- tinctly different situations.

 

 

 

 

 

Figure 8-5:

Using the

pass clause allows for post process­ ing of an

unwanted

input.

 

 

Controlling execution with the else statement

Python has another loop clause that you won’t find with other languages: else. The else clause makes executing code possible even if you have no elements to process in a sequence. For example, you might need to convey to the user that there simply isn’t anything to do. In fact, that’s what the following example does. This example also appears with the downloadable source code as ForElse.py.

 

  1. Open a Python File

You see an editor in which you can type the example code.

2y.peT the following code into the window — pressing Enter after each line:

 

 

 

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 with- out typing something, the else clause is executed.

  1. Choose RunRun

You see a Python Shell window open and a prompt asking for input.

  1. Type Hello and press Enter.

The application lists each character in the string, as shown in Figure 8-2.

  1. Repeat Steps 3 and However, simply press Enter instead of entering any sort of text.

You see the alternative message shown in Figure 8-6 that tells you the string is blank.

 

 

 

 

 

 

 

 

 

 

Figure 8-6:

The else

clause makes it possible to perform

tasks based on an empty sequence.

 

 

It’s easy to misuse the else clause because an empty sequence doesn’t always signify a simple lack of input. An empty sequence could also signal an applica- tion error or other conditions that need to be handled differently from a simple omission of data. Make sure you understand how the application works with data to ensure that the else clause doesn’t end up hiding potential error condi- tions, rather than making them visible so that they can be fixed.