![]() |
![]() |
|
home—info—labs—exams—hws
—D2L—MediaSamples/—breeze (snow day)—tutor/PIs
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) |
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 offset in range(5): px = getPixelAt(pict0, 20, 10+offset) setRed(px,255) setBlue(px,255) |
Hey computer:Or more concisely:
Do the body of the loop — the three indented lines — withoffset being0 .
Then, do the body again with the offset being1 .
Then, do the body again with the offset being2 .
Then, do the body again with the offset being3 .
Then, do the body again with the offset being4 .
Hey computer:What if we change
For every value in the range [0,5),
setoffset to that value
, and do the loop-body.
Notes:
In particular: there is also indentation to indicate what statements are inside a function-definition (as opposed to lines that come after that function definitions). So you must have nested indentation, if you have a for-loop inside a function:
def someFunction(n): print( "hi" ) for i in range(10): print "Yo!" print "i is " + str(i) print( "bye" ) return |
1
The code given here is slightly different than the previous lab —
I have replaced
home—info—labs—exams—hws
—D2L—MediaSamples/—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 ibarland ![]() |
![]() |