RU beehive logo ITEC dept promo banner
ITEC 109
2014spring
ibarland

homeinfolabsexamshws
D2LMediaSamples/breeze (snow day)tutor/PIs

lab27
Loops!
via `range`

In the previous lab, we had a bunch of nearly-repeated code, to make a stripe 5 pixels long1:

px = getPixelAt(pict0, 20, 10+0)
setRed(px,255)
setBlue(px,255)
px = getPixelAt(pict0, 20, 10+1)
setRed(px,255)
setBlue(px,255)
px = getPixelAt(pict0, 20, 10+2)
setRed(px,255)
setBlue(px,255)
px = getPixelAt(pict0, 20, 10+3)
setRed(px,255)
setBlue(px,255)
px = getPixelAt(pict0, 20, 10+4)
setRed(px,255)
setBlue(px,255)
If we wanted to make this stripe be 8 pixels long instead, we could copy/paste and twiddle the numbers three more times. It wouldn't be that bad, but it wouldn't be anything fun either. And if we wanted to make the strip be 100 pixels long, the copy/paste approach suddenly seems very annoying!

We just want to count the offset-from-10 being 0,1,2,3,4. Can't we get the computer to do this counting for us? Yes! That's exactly what computers are good at (and humans are error-prone at). We can re-write the above 15 lines of code into just 4, using a for loop:

for offset in range(5):
  px = getPixelAt(pict0, 20, 10+offset)
  setRed(px,255)
  setBlue(px,255)
This says:
Hey computer:
Do the body of the loop — the three indented lines — with offset being 0.
Then, do the body again with the offset being 1.
Then, do the body again with the offset being 2.
Then, do the body again with the offset being 3.
Then, do the body again with the offset being 4.
Or more concisely:
Hey computer:
For every value in the range [0,5),
  set offset to that value
, and   do the loop-body.
What if we change range(5) to be range(100)? Then offset ranges from 0 up to (but not including) 100, and for each offset we do the loop-body. Yippee!

Notes:


If you have not completed the previous lab, you can check that off up until the end of today (last chance). Then, you can check off the following tasks today, or next time. (We'll also be talking more about loops next time.)

1 The code given here is slightly different than the previous lab — I have replaced 12 with 10+2, and so on. Hey, that's kinda like what you had to do for stripeAtX20, once 10 was replaced with any x!      

homeinfolabsexamshws
D2LMediaSamples/breeze (snow day)tutor/PIs


©2014, Ian Barland, Radford University
Last modified 2014.Mar.20 (Thu)
Please mail any suggestions
(incl. typos, broken links)
to ibarlandradford.edu
Powered by PLT Scheme