Iteration and Looping

Quiz: counts toward finishing the lesson. Check: just for practice.

Iteration

while loops and for loops repeat sections of code.

while loops

A while loop keeps repeating as long as its condition is true. Here's an example:

The loop first tests the condition. If it's true, the code in the loop runs. This repeats until the condition is false, and then execution continues with the code after the loop. Something in the loop must eventually make the condition false. Otherwise the loop runs forever, which is called an infinite loop. This example never stops on its own, so you would have to stop the program yourself.

while True:
    print("hi")

for loops

A for loop goes through a sequence (an iterable type) and repeats once for each element. A loop variable takes on the value of the current element, so you can use it inside the loop. So far, strings are the only iterable type we've seen. We'll see one more on this page and others later. Here's an example that loops through a string:

The first time through the loop, letter equals "a", next time through it equals "p", next "o", and so on until the last time through, when it equals "y".

Using ranges with for loops

If we need a for loop to iterate over some increasing (or decreasing) sequence of integers, we can use a range. Ranges are another iterable type. Here's an example that counts from 1 to 10:

Notice that the range goes from 1 up to, but not including, 11. A range can also count by a given step size:

You can count down by using a negative step size, but if you do, then the first number (the start of the range) needs to be greater than the second number (the end of the range):

Check your understanding. Predict the result. Check whether each range has any numbers in it, and what the step does.

x = 100
y = 0
for x in range(5, 1):
    y += 1
for n in range(10, 0, -3):
    y += n

Predict what each variable holds after the program finishes. The program is not run for you. Change the values below to your predictions:

  • final_x is the value of x at the end
  • final_y is the value of y at the end
Hint 1

A range with no numbers never runs the body, so the loop variable is never set. The second range counts down by 3.

break and continue

The break keyword ends a loop early. For example:

This loop only prints the numbers up to 4 because when break runs, it immediately exits the loop.

The continue keyword skips the rest of the current iteration and jumps to the next one. Try replacing break with continue in the code above. It then prints the numbers from 1 through 10 except for 5.

Check your understanding. Predict the result. Think about what x holds when the loop ends, and which numbers continue skips.

x = 0
y = 0
for x in range(1, 11):
    if x % 3 == 0:
        continue
    y += x

Predict what each variable holds after the program finishes. The program is not run for you. Change the values below to your predictions:

  • final_x is the value of x at the end
  • final_y is the value of y at the end
Hint 1

continue still leaves the loop variable set. The range stops before 11.

Proper use of break

Sometimes break is justified, but try to write your loop conditions so that break is not needed. That usually makes the loop easier to read.

Notice that we changed == to !=. The first version tested when to stop, and the second tests when to keep going.

If two things must be True for a loop to continue, join them with and in the loop condition. If there are more than two, or the condition gets long, you can use break statements to split it across several lines. You can also save a condition in a variable with a descriptive name and use that variable in the loop condition.

Nested loops

Both while loops and for loops can be nested (placed inside other loops). You can also put if statements inside loops and loops inside if statements, to any depth.

Quizzes

  1. Write a function named sum_to that takes an integer parameter n and returns the sum of the integers from 1 to n (inclusive).
  1. Write a function named length_parity that takes a string parameter, counts how many characters are in the string, and returns "odd" if that number is odd and "even" if that number is even.
  1. Write a function named echo_until_quit that takes a list of strings. Starting from the first item, it prints each string on its own line, stopping as soon as it reaches the string "quit" (which is not printed). Then call your function with the list ["red", "green", "quit", "blue"].
  1. Predict the result. Count how many times the inner body reaches x += 1, and what b is at the end.
x = 0
y = 0
for a in range(0, 3):
    for b in range(0, 4):
        if b == 2:
            break
        x += 1
y = b

Predict what each variable holds after the program finishes. The program is not run for you. Change the values below to your predictions:

  • final_x is the value of x at the end
  • final_y is the value of y at the end
Hint 1

break only leaves the inner loop. The outer loop still goes around each time.

Projects

Practice what you learned in your own editor. Each project has its own page.