Introduction: Repetition, repetition, repetition 🔁

So far we've covered 5 of the 6 essential constructs: input, processing, output, sequence, and selection. This module will cover the final construct, repetition. With repetition added to your toolbox you will be able to express any computational algorithm.

Repetition is just the ability to say “Do this a bunch of times” without having to write the actual code out several times. This is merely a convenience when the number of times is 2 or 3, but an absolute necessity when the number of times is, say, a few million.

Repetition constructs are needed because many algorithms involve performing an action not just once, but repeatedly while some condition holds. Repetition comes in a couple of flavours.

First, there are those cases where we want to keep repeating an action while some condition is true. For example keeping the water flowing while the humidity is less than 60%.

Second are those cases where we can calculate exactly how many times we will need to repeat the action. For example: there are 8 customers in the line so I will need to "sell ticket" eight times. Python provides the while statement for the first type of repetition, and the for statement to handle the second type.

The core skill to develop in this module is to be able to use the while and for statements in your programs.

A secondary topic will be the process of writing a program by moving from an English description, to a pseudocode description, and on to a Python program.

  1. The idea: Go back up and repeat some code
  2. The flowchart
  3. The syntax
  4. Hihihi!
  5. Infinite Loops
  6. Validating Input
  7. Repeating a program (without restarting it)
  8. Problem: Repeating calculations
  9. Example: Find the average
  10. Sentinel controlled input
  11. Problem: The guessing game
  12. Aside: Getting "random" numbers
  13. Solution: The Guessing Game
  14. A puzzle: What output does this produce?
  15. Nesting loops
  16. Python's other repetition structure: for loops
  17. Completely artificial example revisited: using for
  18. for vs while
  19. f2c revisited: Fahrenheit to Celsius conversion table using for
  20. Nesting for loops
  21. Example: Draw a square
  22. Module 4 Summary
  23. Brute Force
  24. Simulation
  25. Problem: What are the chances: four children, all girls?
  26. Duelling Incompetents
  27. Factors
  28. Cryptarithms
  29. Python Formatting Guidelines
  30. A list-creating function: range()
  31. Timing programs
  32. Exercise sheet 3
  33. Assignment 4