repetition of a mathematical or computational procedure applied to the result of a previous application, typically as a means of obtaining successively closer approximations to the solution of a problem.
a new version of a piece of computer hardware or software. plural noun: iterations
Two Types of Iteration
‘For’ loops
Used with finite lists of definite length
For each item in this list do something…
‘While’ loops:
Used with unknown or non-finite lists
While a condition is still True, do something to the list…
Making the Difference Memorable
For Loops
This ‘simple’ loop allows us to print out every element of the list in turn:
geographers = ['Rose','Massey','Jefferson']for g in geographers:print(g)
Notice the format:
for x inlist:# ...do something using the current value of x...
While Loops
This loop does the same thing, but differently:
geographers = ['Rose','Massey','Jefferson']g =0while g <len(geographers):print( geographers[g] ) g +=1
Notice the format:
while<some condition is true>:# ...do something...
Nesting Loops
We can use one loop ‘inside’ another loop! What do you think this might print?
geographers = ['Rose','Massey','Jefferson']for g in geographers:for h in g:print(h)
Huh??? Let’s puzzle this out…
Debugging
When you see something completely new, it’s often good to:
Add print(...) statements to see how the values of a variable are changing.
Comment out the parts you don’t understand so that you can focus on the parts you do
Then iteratively add complexity!
Step 1: The ‘Outer Loop’
So I would start off with:
geographers = ['Rose','Massey','Jefferson']for g in geographers:print(g)# for h in g:# print(h)
This prints:
'Rose''Massey''Jefferson'
Step 1: Summing Up
OK, so now we know:
That g is the name of a geographer.
The ‘outer’ loop sets g to the name of a new geographer on each iteration.
So if g is set to 'Rose' what does for h in g: do?
Step 2: The ‘Inner’ Loop
We know change it like this:
for g in geographers:print(g)for h in g:print(h)break# <-- Notice this!
This prints:
RoseRose
Step 2: Summing Up
And now we know that:
h is looping over the string, meaning that a string can be treated as a list!
And break is a really useful way to control a loop while you’re testing your code!
Recap
for iterates once over a collection items (e.g. a list).
while keeps going until a condition is False.
Test Yourself
What will this code print? I’d suggest that you don’t run it!
geographers = ['Rose','Massey','Jefferson']g =0while g <len(geographers):print( geographers[g] )
Test Yourself (Tricksy Version)
Here’s a really tricky one! The following two blocks of code produce the same output, how are they different?
geographers = ['Rose','Massey','Jefferson']geographers.reverse()for g in geographers:print(g)
And:
geographers = ['Rose','Massey','Jefferson']g =len(geographers)-1while g >=0:print( geographers[g] ) g -=1