FOR STATEMENT
In [1]: for character in 'Programming':
...: print(character, end=' ')
...:
P r o g r a m m i n g
The for statement executes as follows:
- Upon entering the statement, it assigns the 'P' in 'Programming' to the target variable between keywords for and in—in this case, character.
- Next, the statement in the suite executes, displaying character’s value followed by two spaces—we’ll say more about this momentarily.
- After executing the suite, Python assigns to character the next item in the sequence (that is, the 'r' in 'Programming'), then executes the suite again.
- This continues while there are more items in the sequence to process. In this case, the statement terminates after displaying the letter 'g', followed by two spaces.
Function print’s end Keyword Argument
print(character, end=' ')
which displays character’s value followed by two spaces. So, all the characters display horizontally on the same line. Python calls end a keyword argument, but end itself is not a Python keyword. Keyword arguments are sometimes called named arguments. The end keyword argument is optional. If you do not include it, print uses a newline ('\n') by default. The Style Guide for Python Code recommends placing no spaces around a keyword argument’s =.
Function print’s sep Keyword Argument
In [2]: print(10, 20, 30, sep=', ')
10, 20, 30
To remove the default spaces, use sep='' (that is, an empty string).
1.1 Iterables, Lists and Iterators
In [3]: total = 0
In [4]: for number in [2, -3, 0, 17, 9]:
...: total = total + number
...:
In [5]: total
Out[5]: 25
Each sequence has an iterator. The for statement uses the iterator “behind the scenes” to get each consecutive item until there are no more to process. The iterator is like a bookmark—it always knows where it is in the sequence, so it can return the next item when it’s called upon to do so. We cover lists in detail in the “Sequences: Lists and Tuples” chapter. There, you’ll see that the order of the items in a list matters and that a list’s items are mutable (that is, modifiable).
1.2 Built-In range Function
In [6]: for counter in range(10):
...: print(counter, end=' ')
...:
0 1 2 3 4 5 6 7 8 9
The function call range(10) creates an iterable object that represents a sequence of consecutive integers starting from 0 and continuing up to, but not including, the argument value (10)—in this case, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. The for statement exits when it finishes processing the last integer that range produces. Iterators and iterable objects are two of Python’s functionalstyle programming features. We’ll introduce more of these throughout the book.