For Statements

Like the while statement, the for statement allows you to repeat an action or several actions. The for statement performs its action(s) for each item in a sequence of items. For example, a string is a sequence of individual characters. Let’s display ‘Programming’ with its characters separated by two spaces:

for character in 'Programming':
	print(character, "  ");

The for statement executes as follows:

  1. Upon entering the statement, it assigns the ‘P’ in ‘Programming’ to the target variable between keywords for and in — in this case, character.

  2. Next, the statement in the body executes, displaying character’s value followed by two spaces.

  3. After executing the body, Python assigns to character the next item in the sequence (that is, the ‘r’ in ‘Programming’), then executes the body again.

  4. 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.

Iterables, Lists and Iterators:

The sequence to the right of the for statement’s in keyword must be an ***iterable***. An iterable is a set of values from which the for statement can take one item at a time until no more items remain. Python has other iterable sequence types besides strings. One of the most common is a *** list***, which is a comma-separated collection of items enclosed in square brackets ([ and ]). The following code totals five integers in a list:
sum = 0
for num in [1, 5, 9, -2, 10]:
	sum = sum + num;

Each for loop has an iterator. 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. For each number in the list, the suite adds the number to the total. When there are no more items to process, total contains the sum (23) of the list’s items. 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).

Range:

Let’s use a for statement and the range statement to iterate precisely 10 times, displaying the values from 0 through 9:
for counter in range(10):
	print(counter)

The statement range(10) creates an iterable object that represents a sequence of consecutive integer values starting from 0 and continuing up to, but not including, the value found inside of the parentheses (10). In this case, the sequence is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. The for statement exits when it finishes processing the last integer that range produces.

Off-By-One Errors

A logic error known as an off-by-one error occurs when you assume that range’s argument value is included in the generated sequence. For example, if you provide 9 as range’s argument when trying to produce the sequence 0 through 9, range generates only 0 through 8.