### CS12 : Iteration, Iteration, Iteration

Finally, the third major programming construct, iteration. Iteration is simply a fancy word for repeating something. In this topic, we will look at the two iteration methods built into Python plus look quickly at two which aren't.

 Learning OutcomesIteration, Iteration, Iteration

We are learning ...
• How to use definite and indefinite iteration
So that we can ...
• Describe and use iteration
- definite iteration
- indefinite iteration
• See examples of iteration in use
- Read values from and write values to lists
- Totalling
- Counting
- Handling tables (nested iteration)

 Activity 1What is iteration?

Iteration is a process in which you repeat somethings lots of times until you reach some specified goal. Iteration is used extensively in maths, in product design and in software engineering.

Task 1.1 Design as an iterative process
Where we learn about the concept of iteration

As a class

Watch the video and think about how you can apply these principles to software design. Be prepared to discuss your ideas with the rest of the class.

The iterative development of the mobile phone

Where we learn about the different synonyms for iteration (and how to spot it)

In your notebooks / on paper

Copy the mind map into your notebooks. Can you think of any more words to add to it?

Click to engage

 Activity 2Definite iteration (Count Controlled Loops)

With definite iteration, we know in advance how many times our loop will run. This is known as a FOR ... NEXT loop. In Python, we define a for loop ...

 `f``or VALUE in LIST:   # VALUE is temporary variable. LIST is anything that generates a list` `  for_body           # Executes for as many items as there are in LIST` `[else:               # Optional else clause - zero or one of these allowed` `  else_body]         # Executes only if loop ends normally, i.e. no 'break'`

The values in LIST can be any Python sequence type - lists (including dictionaries), tuples or ranges.

 `list = [item, item, ...]` `dictionary = {key:value, key:value, ...}` `tuple = (item, item, ..``.)`

It is also possible to break out of definite iteration early using the `break` function. This would normally be found in a selection within the loop body. Note that in this case, the optional else clause will never execute. There may also be some situations where we want to continue looping without executing part of the `for_body` - in this case, we can use the `continue` function.

Task 2.1 Focus on the `range()` function
Where we learn how to use the Python range function

In Python, the `range()` function is used to represent a range of numbers. It does not, in itself, create a range of numbers until it is executed - it is a 'lazy' function. The range command itself has the following syntax ...

 `range([start=0,]stop[,step=1])`

... where `start` is optional but defaults to `0`, `stop` is required and `step` is optional but defaults to `1`. If you need to specify `step` you must also specify `start` or else the `range()` function will get confused, so valid structures are ...

 `range(stop)` `range(start,stop`) `range(start,stop,step`)

NOTE : The range function will not generate the actual value of stop within its sequence;

For the following task, create a blank word processed document and use a combination of screenshots and written explanation to evidence what you have done and what you have learnt.

Firstly, open up the Python programming environment, IDLE.

At the Python prompt

Type the following commands, pressing the  ENTER  key after each one. Discuss what happens with your shoulder partner. As some of these are quite tricky to understand, your teacher might demonstrate this to you first.

`>>>`` range(10)`
`>>> list(range(10))`
`>>> range(2,10)`
`>>> list(range(2,10))`
`>>> 6 in range(10)`
`>>> 10 in range(10)`
`>>> 12 in range(10)`
`>>> r = range(0,20,2)`
`>>> list(r)`
`>>> r[5]`
`>>> r[-2]`
`>>> r.index(8)`
`>>> 12 in r`
`>>> 13 in r`
`>>> list(r[:5])`
`>>> s = range(20,0,-2)`
`>>> list(s)`
`>>> list(range(0,30,3))`
`>>> list(range(30,3,-3))`

At the prompt / in your notebooks

Create a `range``()` object for each of the following situations. Use the `list()` function to demonstrate the actual numbers which exist in your range. The first one has been done for you. Record your `range()` object clearly in your notebook.

Q1 : Generate a list of numbers from 1 to 10 ... A1`list(range(1,11))`
Q2
: Generate a list of all even numbers from 2 to 14
Q3 : Generate a list of all odd numbers from 1 to 11
Q4 : Generate a list of numbers counting down from 20 to 0 in steps of 2
Q5 : Generate a list containing the last five numbers in the sequence containing numbers 0 to 30 in steps of 3

Where we learn how to use definite iteration

It's difficult to demonstrate how iteration works without giving you practical examples to try first.

Through a series of Python scripts

Download the file 'definite.zip' to a suitable location in your user space. Find the file, and extract its contents by right clicking and choose 'Extract' from the menu. When the extraction is completed, delete the original zip file. You should find 9 scripts in the folder ...

01. Print every item in a range.py
02. Printing letters in a string.py
03. Printing items from a list.py
04. Printing items from a dictionary.py
05. Printing items from a tuple.py
06. Printing every nth item from a string.py
07. Breaking out of a for loop.py
08. Printing a times table square.py
09. Skipping letters.py

On the worksheet

Download the worksheet 'Definite iteration'. Fill in your details in the document header. You will need to use this worksheet to record what you have done in the next step of this task.

Open up each Python file in the folder in IDLE by right clicking on the script and choosing 'Edit with IDLE'. First, inspect the script, rubber duck it to your shoulder partner and then run it.

Quack!

Complete the relevant part of the worksheet before moving on to the next script. Repeat this process until you have looked at all 9 scripts in the folder.

Now print out the worksheet single sided and stick it in your notebook

Where we learn how to draw a general flowchart segment for definite iteration

It's not so easy representing definite iteration with a flowchart - standard flowchart symbols don't include a single symbol for definite iteration so we need to step back a little and look at exactly how definite iteration works.

In your notebooks / on paper

Copy the following flowchart segment manually (i.e. with a pen / pencil) into your notebooks / onto paper. Take care when you are drawing it that you include all the labels on lines as well as the ones in the symbols.

The symbols in  YELLOW  form the structure of the `for` loop whereas the subprocess in  GREEN  is the `for_body` and the subprocess in  GREY  is the optional `else_body`. Notice that if you `break` manually out of the `for` loop, you skip over the `else_body`. The optional `continue` could skip over part of the `for_body` and continue execution of the loop at the next value.

In your notebooks / on paper

Now inspect the flowchart carefully, turn to the back of your notebook and sketch the flowchart out again. Repeat this process until you can draw it out from memory - that way you'll remember it more easily.

 Activity 3Indefinite iteration (Condition Controlled Loops)

With indefinite iteration, it is not possible to tell in advance how many times we will need to repeat the operations in the body. We generally carry on looping while the result of some condition / test evaluates to `True` or we issue a manual `break` instruction. This is known as a WHILE ... DO loop but in Python ...

 `while DECISION_STATEMENT:` `  while_body               # Executes only if DECISION_STATEMENT evaluates to True` `[else:                     # Optional else clause - zero or one of these allowed` `  else_body]               # Executes only if loop ends normally and no break`

It is also possible to break out of indefinite iteration early using the `break` function. This would normally be found in a selection within the while loop body. Note that in this case, the optional `else` clause will never execute. There may also be some situations where we want to continue looping without executing part of the `while_body` - in this case, we can use the `continue` function.

Where we learn how to program some practical examples of indefinite iteration

Again, it's difficult to demonstrate how indefinite iteration works without giving you practical examples to try first.

Through a series of Python scripts

Download the file 'indefinite.zip' to a suitable location in your user space. Find the file, and extract its contents by right clicking and choose 'Extract' from the menu. When the extraction is completed, delete the original zip file. You should find 8 scripts in the folder ...

01. A while loop like a for loop.py
02. An infinite loop.py
04. Rogue value.py
05. Enter a valid number.py
06. Use a while loop to create a list.py
07. Using a while loop to add up values in a list.py
08. Skipping over things.py

On the worksheet

Download the worksheet 'Indefinite iterationand save it in a suitable place in your documents. Fill in your details in the document header. You will need to use this worksheet to record what you have done in the next step of this task.

Open up each Python file in the folder in IDLE by right clicking on the script and choosing 'Edit with IDLE'. First, inspect the script, rubber duck it to your shoulder partner and then run it.

Complete the relevant part of the worksheet before moving on to the next script. Repeat this process until you have looked at all 8 scripts in the folder.

Now print out the worksheet single sided and stick it in your notebook.

Where we learn how to draw a generic flowchart segment for indefinite iteration

Representing a while loop with a flowchart is much easier than it is to represent a `for` loop - thankfully!

In your notebooks / on paper

Copy the following flowchart segment manually (i.e. with pen / pencil) into your notebooks onto paper. Like before, take care when drawing the symbols and lines that you include all the labels.

Again, the symbols in  YELLOW  form the structure of the `while` loop whereas the subprocess in  GREEN  represents the `while_body`. The subprocess in  GREY  represents the optional `else_body` which *could* execute after successful completion of the `while` loop. Notice that a manual `break` operation will skip over this optional `else_body`. The optional `continue` statement could skip over part of the `while_body` and continue execution of the loop.

In your notebooks / on paper

Now inspect the flowchart carefully, turn to the back of your notebook and sketch the flowchart out again. Repeat this process until you can draw it out from memory - that way you'll remember it more easily.

Task 3.3 Caveat on REPEAT ... UNTIL and DO ... WHILE
Where we learn about indefinite iteration structures that Python does not support

Lots of other programming languages have a couple of extra indefinite iteration structures called ...
• REPEAT ... UNTIL which executes a `repeat_body` until a condition is `True`
• DO ... WHILE which executes a `do_body` whilst a condition is `True`
Python does not but, suffice to say, if it did, their flowcharts might look like this ...

The REPEAT ... UNTIL and DO ... WHILE structures check for a condition at the end of the loop and exits gracefully if the condition is `True` or `False` respectively. In this way, they will always execute the `body` at least once. We can create a similiar structures using a `while` loop in Python, so it's not really necessary to have any extra iteration structures.

Write a brief description of both the REPEAT ... UNTIL and DO ... WHILE structures based on the flowcharts in your notebooks and, if you can, explain why Python does not need either of these two structures.

NESTED Iteration and the Twelve days of christmas

https://codeshare.io/axx7gP

 Assessment Task (Homework) You've met 17 (count 'em) different situations where either definite or indefinite iteration can be used. Whilst you were looking at the scripts in the two exercises, I hope that you were thinking of other situations where these techniques could be used (if you weren't, you weren't engaged!) Based on the examples I have given you, come up with two different examples of definite iteration and two different examples of indefinite iteration and write your own scripts to demonstrate your ideas. Present your scripts together with evidence of their output and a description of how they work in your notebooks. Grading rubric A : You have created four scripts using substantially different situations than I used, have demonstrated them working and written about how they operate. Your explanations are clear and concise. C : You have created four scripts based on the ones I have given you, have demonstrated how they work but your descriptions are a little vague. E : You have basically copied four of my scripts and tweaked them by altering the loop variables or prompts. You have provided a screenshot of the script in operation but have not really described how they work.