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

homeinfolabsexamshws
D2LMediaSamples/breeze (snow day)tutor/PIs

lab33
Accumulating an answer

We have used for (and, range) to loop over images, changing them (but not returning an answer). Today, we'll use them to build up an answer to a problem.

You may have noticed something odd about the sequence of problems we've done this semester: Once we learned about functions and def, we had functions that returned an answer. Then, when we reached turtles and pictures, all our functions modified the state of the turtle/picture, but didn't return an answer — they all were # → None. Today we'll resume functions that return a value.

In particular, we'll see that we can reassign to a variable, to build up an answer over time. We'll call this “accumulating an answer”, and we might even talk about an “accumulator variable”. (This is not a widely-used term, but it is a helpful notion.)

Example: stringTimes. Suppose I want to build up five copies of the word "hello", to get "hellohellohellohellohello". Here's one way to do it:

stringSoFar = ""  # one-time setup

stringSoFar = stringSoFar + "hello"
stringSoFar = stringSoFar + "hello"
stringSoFar = stringSoFar + "hello"
stringSoFar = stringSoFar + "hello"
stringSoFar = stringSoFar + "hello"
At this point, stringSoFar contains the result we want.

Clearly, we could make five copies of any string. If we put the original string in a variable:

txtToRepeat = "hello"
stringSoFar = ""  # one-time setup

stringSoFar = stringSoFar + txtToTRepeat
stringSoFar = stringSoFar + txtToTRepeat
stringSoFar = stringSoFar + txtToTRepeat
stringSoFar = stringSoFar + txtToTRepeat
stringSoFar = stringSoFar + txtToTRepeat

Finally, we realize that if we want to repeat the same statement five times, we can put it inside a loop:

  numCopies = 5
  txtToRepeat = "hello"
  stringSoFar = ""  # one-time setup
  for currentCopyNumber in range(numCopies):
    stringSoFar = stringSoFar + txtToTRepeat

YOUR TASK: next time, Write a function doublePairs: doublePairs("abcdef") = "ababcdcdefef"

(Examples will be provided as a test-function, next time.)

homeinfolabsexamshws
D2LMediaSamples/breeze (snow day)tutor/PIs


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