Conditional repetition: the while-loop

Python has two types of loop: for-loops and while-loops. We've already briefly encountered for-loops back when we introduced significant whitespace, and we'll return to them soon, but right now we'll cover while-loops.

The While-loops in Python are introduced by the while keyword, which is followed by a boolean expression. As with the condition for if-statements, the expression is implicitly converted to a boolean value as if it has been passed to the bool() constructor. The while statement is terminated by a colon because it introduces a new block.

Let's write a loop at the REPL which counts down from five to one. We'll initialize a counter variable called c to five, and keep looping until we reach zero. Another new language feature here is the use of an augmented-assignment operator, -=, to subtract one from the value of the counter on each iteration. Similar augmented assignment operators exist for the other basic math operations such as addition and multiplication:

>>> c = 5
>>> while c != 0:
... print(c)
... c -= 1
...
5
4
3
2
1

Because the condition — or predicate — will be implicitly converted to bool, just as if a call to the bool() constructor were present, we could replace the above code with the following version:

>>> c = 5
>>> while c:
... print(c)
... c -= 1
...
5
4
3
2
1

This works because the conversion of the integer value of c to bool results in True until we get to zero which converts to False. That said, to use this short form in this case might be described as un-Pythonic, because, referring back to the Zen of Python, explicit is better than implicit. We place higher value of the readability of the first form over the concision of the second form.

The While-loops are often used in Python where an infinite loop is required. We achieve this simply by passing True as the predicate expression to the while construct:

>>> while True:
... print("Looping!")
...
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!
Looping!

Now you're probably wondering how we get out of this loop and regain control of our REPL! Simply press Ctrl+C:

Looping!
Looping!
Looping!
Looping!
Looping!
Looping!^C
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
>>>

Python intercepts the key stroke and raises a special exception which terminates the loop. We'll be talking much more about what exceptions are, and how to use them, later in Chapter 6Exceptions.

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

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