Processing Data Using the while Statement
You use the while statement for situations when you’re not sure how much data the application will have to process. Instead of instructing Python to process a static number of items, you use the while statement to tell Python to continue processing items until it runs out of items. This kind of loop is useful when you need to perform tasks such as downloading files of unknown size or streaming data from a source such as a radio station. Any situation in which you can’t define at the outset how much data the application will pro- cess is a good candidate for the while statement that is described more fully in the sections that follow.
Understanding the while statement
The while statement works with a condition rather than a sequence. The condition states that the while statement should perform a task until the condition is no longer true. For example, imagine a deli with a number of cus- tomers standing in front of the counter. The salesperson continues to service customers until no more customers are left in line. The line could (and proba- bly will) grow as the other customers are handled, so it’s impossible to know at the outset how many customers will be served. All the salesperson knows is that continuing to serve customers until no more are left is important. Here is how a while statement might look:
The statement begins with the while keyword. It then adds a condition. In this case, a variable, Sum, must be less than 5 for the loop to continue.
Nothing specifies the current value of Sum, nor does the code define how the value of Sum will change. The only thing that is known when Python executes the statement is that Sum must be less than 5 for the loop to continue per- forming tasks. The statement ends with a colon and the tasks are indented below the statement.
Because the while statement doesn’t perform a series of tasks a set number of times, creating an endless loop is possible, meaning that the loop never ends. For example, say that Sum is set to 0 when the loop begins, and the ending condition is that Sum must be less than 5. If the value of Sum never increases, the loop will continue executing forever (or at least until the com- puter is shut down). Endless loops can cause all sorts of bizarre problems on systems, such as slowdowns and even computer freezes, so it’s best to avoid
them. You must always provide a method for the loop to end when using a while loop (contrasted with the for loop, in which the end of the sequence determines the end of the loop). So, when working with the while statement, you must perform three tasks:
- Create the environment for the condition (such as setting Sum to 0).
- State the condition within the while statement (such as Sum < 5).
- Update the condition as needed to ensure that the loop eventually ends (such as adding Sum+=1 to the while code block).
As with the for statement, you can modify the default behavior of the while statement. In fact, you have access to the same four clauses to modify the while statement behavior:
- break: Ends the current
- continue: Immediately ends processing of the current
- pass: Ends processing of the current element after completing the state- ments in the if
- else: Provides an alternative processing technique when conditions aren’t met for the
Using the while statement in an application
You can use the while statement in many ways, but this first example is straightforward. It simply displays a count based on the starting and ending condition of a variable named Sum. The following steps help you create and test the example code. This example also appears with the downloadable source code as SimpleWhile.py.
- 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 code demonstrates the three tasks you must perform when working with a while loop in a straightforward manner. It begins by set- ting Sum to 0, which is the first step of setting the condition environment. The condition itself appears as part of the while statement. The end of the while code block accomplishes the third step. Of course, the code displays the current value of Sum before it updates the value of Sum.
A while statement provides flexibility that you don’t get with a for state- ment. This example shows a relatively straightforward way to update Sum. However, you can use any update method required to meet the goals of the application. Nothing says that you have to update Sum in a specific manner. In addition, the condition can be as complex as you want it to be.
For example, you can track the current value of three or four variables if so desired. Of course, the more complex you make the condition, the
more likely it is that you’ll create an endless loop, so you have a practical limit as to how complex you should make the while loop condition.
- Choose Run➪Run
Python executes the while loop and displays the numeric sequence shown in Figure 8-7.
Figure 8-7: The simple while loop dis plays a sequence of numbers.
Nesting Loop Statements
In some cases, you can use either a for loop or a while loop to achieve the same effect. The manners work differently, but the effect is the same. In this example, you create a multiplication table generator by nesting a while loop within a for loop. Because you want the output to look nice, you use a little formatting as well (Chapter 11 provides you with detailed instruction in this regard). This example also appears with the download- able source code as ForElse.py.
- 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 begins by creating two variables, X and Y, to hold the row and column value of the table. X is the row variable and Y is the column variable.
To make the table readable, this example must create a heading at the top and another along the side. When users see a 1 at the top and a 1 at the side, and follow these values to where they intersect in the table, they can see the value of the two numbers when multiplied.
The first print() statement adds a space (because nothing appears in the corner of the table; see Figure 8-8 to more easily follow this discus- sion). All the formatting statement says is to create a space 4 characters wide and place a space within it. The {:>4} part of the code determines the size of the column. The format(‘ ‘) function determines what appears in that space. The end attribute of the print() statement changes the ending character from a carriage return to a simple space.
The first for loop displays the numbers 1 through 10 at the top of the table. The range() function creates the sequence of numbers for
you. When using the range() function, you specify the starting value, which is 1 in this case, and one more than the ending value, which is 11 in this case.
At this point, the cursor is sitting at the end of the heading row. To move it to the next line, the code issues a print() call with no other information.
Even though the next bit of code looks quite complex, you can figure it out if you look at it a line at a time. The multiplication table shows the values from 1 * 1 to 10 * 10, so you need ten rows and ten columns to display the information. The for statement tells Python to create ten rows.
Look again at Figure 8-8 to note the row heading. The first print() call displays the row heading value. Of course, you have to format this information, and the code uses a space of four characters that end with
a space, rather than a carriage return, in order to continue printing infor- mation in that row.
The while loop comes next. This loop prints the columns in an indi- vidual row. The column values are the multiplied values of X * Y. Again, the output is formatted to take up four spaces. The while loop ends when Y is updated to the next value using Y+=1.
Now you’re back into the for loop. The print() statement ends the current row. In addition, Y must be reset to 1 so that it’s ready for the beginning of the next row, which begins with 1.
- Choose Run➪Run
You see the multiplication table shown in Figure 8-8.
Figure 8-8: The multipli cation table is pleasing to the eye thanks to its formatting.