![]() |
![]() |
|
home—info—labs—exams—hws
—D2L—MediaSamples/—breeze (snow day)—tutor/PIs
We have used
You may have noticed something odd about the sequence of problems we've done this semester:
Once we learned about functions and
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:
stringSoFar = "" # one-time setup stringSoFar = stringSoFar + "hello" stringSoFar = stringSoFar + "hello" stringSoFar = stringSoFar + "hello" stringSoFar = stringSoFar + "hello" stringSoFar = stringSoFar + "hello" |
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
home—info—labs—exams—hws
—D2L—MediaSamples/—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 ibarland ![]() |
![]() |