The while loop

while loops are quite similar to for loops, with one major distinction: they don't need an iterable to run over—instead, they are driven by a simple Boolean value. While this value is true, the loop will continue to run, potentially an infinite number of times. Consider the following example. Here, we run a while loop until the counter value is less than 5. Once that is no longer the case, the loop stops. As the initial value of the variable is zero, it is easy to deduce that the loop ran five times:

counter = 0
while counter < 5:
print(counter)
counter += 1

Be careful! It is easy to make this loop infinite by accident. In some cases, however, that is exactly what we want, so we can make this explicit through the pattern:

while True:
compute()

The preceding loop is explicitly infinite: it will run forever, or, realistically, until something stops the script—either from inside (code error), or outside (you terminating the script, or the computer rebooting). This pattern is useful for continuous tasks—for example, collecting data from the streaming endpoint.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.162.65