CP104 Notes: for Loops

The for Loop

The for loop is an example of an iteration loop. This means it iterates (i.e. walks) through every element of a sequence.

Syntax:

    
for target in range([start,] end[, increment]):
    statement
    [statements]

  
target
is the variable generated by the Python for based upon the range given
range
is a Python function that generates and returns a sequence of values based upon its arguments. It is often used to force a for loop to execute a set number of times.
start
is the starting value of the generated range. This value is optional and defaults to 0.
end
is the value after the end of the generated range (i.e. the numbers generated go up to, but not including, end). This value is required.
increment
is the difference between each value in the range. This value is optional and defaults to 1. This value can only be used if both the start and end values are set.

Two simple example:

    
n = 10

for i in range(n):
    print(f"{i}, ", end="")
print()

  

prints:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9,

and:

    
n = 10

for i in range(n - 1, -1, -1):
    print(f"{i}, ", end="")
print()

  

prints:

9, 8, 7, 6, 5, 4, 3, 2, 1, 0,

Rules for for Loops

These are the general rules to following when using for loops:

Note that breaking these rules does not violate Python syntax - all these sample codes still execute without error - but they demonstrate a lack of understanding of how for loops in Python actually work.


for vs while Loops

All for loops can be rewritten as while loops, but the reverse is not true. for loops should used when:

while loops should used when:


for Loops with Strings and Lists

A for loop allows you to loop item by item all the way through a sequence of items. This means that you can use the for loop to:

Don't mix the two uses together. Example:

You have a simple list:

      
numbers = [7, 3, 0, 2]

    

and you are asked to count the number of 0s in the list. Here is a typical wrong way to do it:

      
for i in numbers:
    if numbers[i] == 0:
        zero_count += 1

    

This is wrong because i is not an index. The i in each iteration of the loop contains the values in the list numbers one after another. Thus the line

      
  if numbers[i] == 0:

    

is executed as this:

  if numbers[7] == 0: ...
  if numbers[3] == 0: ...
  if numbers[0] == 0: ...
  if numbers[2] == 0: ...

which, of course, dies on the first try, because there is no element of numbers with the index 7.

Here are two correct approaches:


Things To Avoid

"Are We There Yet" Code

The following code performs more work than is necessary:

      
for i in range(n):

    if i == 0:
        # process the first value
        v = int(input("First value: "))
    elif i == n - 1:
        # process the last value
        v = int(input("Last value: "))
    else:
        # process intermediate value
        v = int(input("Next value: "))

    

Although this code 'works' in the sense that it correctly asks the user for all values that it should, it is the programming equivalent of children constantly asking their parents, "Are we there yet?", on a car trip. The loop is checking for very specific occurrences that happen only once, and should happen at the beginning or end of the loop.

A much better approach is to remove from the loop the code that is executed only once, and place it before or after the loop definition as appropriate:

      
# process the first value
v = int(input("First value: "))

for i in range(1, n - 1):
    # process intermediate value
    v = int(input("Next value: "))

# process the last value
v = int(input("Last value: "))

    

This principle applies to while loops as well.