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.
- The idea: Go back up and repeat some code
- The flowchart
- The syntax
- Hihihi!
- Infinite Loops
- Validating Input
- Repeating a program (without restarting it)
- Problem: Repeating calculations
- Example: Find the average
- Sentinel controlled input
- Problem: The guessing game
- Aside: Getting "random" numbers
- Solution: The Guessing Game
- A puzzle: What output does this produce?
- Nesting loops
- Python's other repetition
structure:Â
for
 loops - Completely artificial example revisited: using for
for
 vsÂwhile
- f2c revisited: Fahrenheit to Celsius conversion table
usingÂ
for
- NestingÂ
for
 loops - Example: Draw a square
- Module 4 Summary
- Brute Force
- Simulation
- Problem: What are the chances: four children, all girls?
- Duelling Incompetents
- Factors
- Cryptarithms
- Python Formatting Guidelines
- A list-creating
function:Â
range()
- Timing programs
- Exercise sheet 3
- Assignment 4