4. More Control Flow Tools
Besides theÂ whileÂ statement just introduced, Python knows the usual control flow statements known from other languages, with some twists.
4.1.Â ifÂ Statements
Perhaps the most well-known statement type is theÂ ifÂ statement. For example:
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... elif x == 1:
There can be zero or moreÂ elifÂ parts, and theÂ elseÂ part is optional. The keyword â€˜elifâ€˜ is short ...view middle of the document...
... if len(w) > 6:
... words.insert(0, w)
['defenestrate', 'cat', 'window', 'defenestrate']
4.3. TheÂ range()Â Function
If you do need to iterate over a sequence of numbers, the built-in functionÂ range()Â comes in handy. It generates arithmetic progressions:
>>> for i in range(5):
The given end point is never part of the generated sequence;Â range(10)Â generates 10 values, the legal indices for items of a sequence of length 10. It is possible to let the range start at another number, or to specify a different increment (even negative; sometimes this is called the â€˜stepâ€™):
5 through 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70
To iterate over the indices of a sequence, you can combineÂ range()Â andÂ len()Â as follows:
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
In most such cases, however, it is convenient to use theÂ enumerate()Â function, seeÂ Looping Techniques.
A strange thing happens if you just print a range:
In many ways the object returned byÂ range()Â behaves as if it is a list, but in fact it isnâ€™t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesnâ€™t really make the list, thus saving space.
We say such an object isÂ iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that theÂ forÂ statement is such anÂ iterator. The functionÂ list()Â is another; it creates lists from iterables:
[0, 1, 2, 3, 4]
Later we will see more functions that return iterables and take iterables as argument.
4.4.Â breakÂ andÂ continueÂ Statements, andÂ elseÂ Clauses on Loops
TheÂ breakÂ statement, like in C, breaks out of the smallest enclosingÂ forÂ orÂ whileÂ loop.
Loop statements may have anÂ elseÂ clause; it is executed when the loop terminates through exhaustion of the list (withÂ for) or when the condition becomes false (withÂ while), but not when the loop is terminated by aÂ breakÂ statement. This is exemplified by the following loop, which searches for prime numbers:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... # loop fell through without finding a factor
... print(n, 'is a prime number')
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
(Yes, this is the correct code. Look closely:...