The forloop is another control-flow statement in Python; it allows a program to repeatedly execute a block of code. The process of doing the same thing repeatedly is called iteration. Want to traverse a list and do some computation with each element? Use a for-loop. Want your program to do something a set number of times? Use a for loop.

Lessons - watch before lecture

  1. The For-Loop (8 minutes) Anatomy of the for loop
  2. For-Loop Design (6 minutes) Some examples of using for loops on lists (stub1.py, accum1.py)
  3. Range-Based For-Loops (9 minutes) Use a for loop to perform definite iteration--repeating some action a set number of times

Optional reading 4.2 and 10.3


Lecture materials

Slides: individual slides for viewing, 6-up layout for printing

Examples: forLoops.py
To download the above .py files, right-click (Windows) or command-click (Macs) on the filename and then select "Save link as".
This way you choose where the files will be saved, instead of having your computer save to the default folder (from which you will later have to move your files for organization).

Lecture Recording

Answers to the questions on slides 16, 25, and 37: See the lecture slides file above for the questions. After solving the problems yourself, you can check your answers here.