Why to while

The while loop is useful for these situations:

• Event-driven programs: Many programs wait for a user to take an action (such as clicking a mouse button), and then respond to the action. Often, a main while loop collects user actions (events) and sends them to chunks of code that act on particular events (event handlers).

• Loops that need to run an undetermined number of times: If you don't know how much data you need to process—for example, when you're reading a binary file—you might use a while loop that repeats its action until it detects that there is no more data.

• Processing a container object while modifying it: The spider.py program in Chapter 4 includes this kind of while block. The block uses the pop() list method to removes items from the links_to_process list. A while loop is used because no matter how long links_to_process is, it will run as long as there are items left in the list. However, it's important that the while block removes items from the list. If it didn't, the code would run forever.

The while loop, because it includes a Boolean expression, can stop unexpectedly if it encounters data (such as None) that evaluates as false. This while loop stops in the middle of processing the list because data is given the value None, which evaluates as false:

The correct way to process items from a list in a while loop is as follows:

Was this article helpful?

0 0

Post a comment