8.5. while StatementPython's while is the first looping statement we will look at in this chapter. In fact, it is a conditional looping statement. In comparison with an if statement where a true expression will result in a single execution of the if clause suite, the suite in a while clause will be executed continuously in a loop until that condition is no longer satisfied. 8.5.1. General SyntaxHere is the syntax for a while loop: while expression: The suite_to_repeat clause of the while loop will be executed continuously in a loop until expression evaluates to Boolean False. This type of looping mechanism is often used in a counting situation, such as the example in the next subsection. 8.5.2. Counting Loopscount = 0 The suite here, consisting of the print and increment statements, is executed repeatedly until count is no longer less than 9. With each iteration, the current value of the index count is displayed and then bumped up by 1. If we take this snippet of code to the Python interpreter, entering the source and seeing the resulting execution would look something like: >>> count = 0 8.5.3. Infinite LoopsOne must use caution when using while loops because of the possibility that the condition never resolves to a false value. In such cases, we would have a loop that never ends on our hands. These "infinite" loops are not necessarily bad thingsmany communications "servers" that are part of client/server systems work exactly in that fashion. It all depends on whether or not the loop was meant to run forever, and if not, whether the loop has the possibility of terminating; in other words, will the expression ever be able to evaluate to false? while True: For example, the piece of code above was set deliberately to never end because TRue is not going to somehow change to False. The main point of this server code is to sit and wait for clients to connect, presumably over a network link. These clients send requests which the server understands and processes. After the request has been serviced, a return value or data is returned to the client who may either drop the connection altogether or send another request. As far as the server is concerned, it has performed its duty to this one client and returns to the top of the loop to wait for the next client to come along. You will find out more about client/server computing in Chapter 16, "Network Programming" and Chapter 17, "Internet Client Programming." |
Tuesday, October 20, 2009
Section 8.5. while Statement
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment