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:
whileloopsforloops
Iterations provide more complexity to our programs and make them more interesting.
Generally an iteration (loop) has two parts:
- Boolean test - an expression that evaluates to
TrueorFalse - 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.
Image reproduced from Chapter 2: Introduction to Computation and Programming Using Python.