Print "hello" three times.
print "hello"
print "hello"
print "hello"
Print "hello" a thousand times--
Probably don't want to type print 1000 times.
Use a loop. Set up a loop variable to keep track of how many times you've printed. Start it at 0 and increment each time inside the loop.
i=0
while (i<1000):print "hello"
i=i+1Note that the loop variable can be called anything. By convention, programmers often use 'i', which is short for index (because we often index into a list, as you'll see below).
Trace the above program. Set up a memory cell for i. Show how i changes.
Lets call the above loop the standard loop template:
initialize loop variable
loop while loop variable is less than some valuedo something
increment loop variableYour count greens robot program had a similar loop in it. What was that code?
Adding a sequence of numbers and processing a list
Consider a list of numbers that a program has obtained somehow. For example, the numbers might be the cost of each grocery item in a cart, or the grade points earned by a student for each class. For this discussion, let's just consider an arbitrary list:
list = [3,6,1,9]
Remember, we can access list items with an index. So we can add up these numbers with the following:
total = list[0]+list[1]+list[2]+list[3]
But like in the printing example above, this only works if we know the list is a certain size. And note that the programmer writing, say, a grade point average program, has no idea how many grades will be in the list.
To total lists of an arbitrary size, we need an accumulator variable.
Think about how you add a sequence of numbers in your head:
Put the first in your head. Add it together with the next number and put the result back in your head. Contniue.
In programming, 'put something in your head' means to create a variable. We can call the variable anything, but 'total' makes sense for an accumlator variable.
So if we have a list of numbers, we can add them in the following way:
list = [3,6,1,9,12,56] # a random list of numbers
# here's the adding part
total = list [0] # put the first number in your head
total = total+ list[1] # add it together with the next number
total = total+list[2]
total = total+list[3]
total = total+list[4]
total = total+list[5]Of course, this only works for a list of six items. So we need to add a loop and a loop variable.
i=0
while (i< ):i=i+1
Fill in the above. How many times do we want to loop? What do we want to do each iteration?
The above is an example of a standard list processing loop as well as an accumulator program.
The factorial program was another example of a accumulator program.
Instructor: program factorial.
How about a program to double each value in a list?