The while
statement is a more general iteration than the for
statement. We'll use a while
loop in two situations. We'll use this in cases where we don't have a finite collection to impose an upper bound on the loop's iteration; we may suggest an upper bound in the while
clause itself. We'll also use this when writing a "search" or "there exists" kind of loop; we aren't processing all items in a collection.
A desktop application that accepts input from a user, for example, will often have a while
loop. The application runs until the user decides to quit; there's no upper bound on the number of user interactions. For this, we generally use a while True:
loop. Infinite iteration is recommended.
If we want to write a character-mode user interface, we could do it like this:
quit_received= False while not quit_received: command= input("prompt> ") quit_received= process(command)
This will iterate until the quit_received
variable is set to True
. This will...