Unit 4 - Iteration (Loops)

In the previous module, we looked at how we could write more complicated problems using conditionals (if statement, etc...).

In addition, we can make our programs repeat particular steps by looping (iteration).

Python has two basic loop statements:

  • while loops
  • for loops

Iterations provide more complexity to our programs and make them more interesting.

Generally an iteration (loop) has two parts:

  1. Boolean test - an expression that evaluates to True or False
  2. Loop body - a block of code that is executed if the test evaluates to True

 

The following image demonstrates the program flow of a basic iteration program.

You can see that the code enters the iteration (dotted box) and encounters the Test, if this evaluates to True it runs the loop body and then repeats the test. If it evaluates to False the program continues.

Flow chart for conditional statement Image reproduced from Chapter 2: Introduction to Computation and Programming Using Python.