Repeating with Numbers

We are going to use a for loop. A for loop is one type of loop or way to repeat a statement or set of statements in a program. A for loop will use a variable and make the variable take on each of the values in a list of numbers one at a time. A list holds values in an order.

Notice that line 3 in the program below ends with a : and that line 4 is indented four spaces so that it starts under the n in number. Indented means that text on the line has spaces at the beginning of the line so that the text doesn’t start right at the left boundary. Both the : and the indention are required in a loop. Line 3 is the start of the for loop and line 4 is the body of the loop. The body of the loop is repeated for each value in the list things_to_add.

What is the sum of all the numbers between 1 and 10? Run the program below to calculate the answer.

    csp-7-2-1: What is printed if you change the program above so that line 5 is also indented the same amount as line 4?
  • It prints the same thing it did before.
  • Did you actually try it?
  • It prints the value of sum 10 times and sum is different each time it is printed.
  • Both lines 4 and 5 are now in the body of the loop and are executed each time through the loop.
  • It prints the same sum 10 times.
  • Sum should be changing.
  • You get an error.
  • You can have more than one line in the body of a loop.
    csp-7-2-2: What is printed if you change the program above so that lines 4 and 5 are not indented?
  • It prints the same thing it did before.
  • Did you actually try it?
  • It prints the value of sum 10 times and sum is different each time it is printed.
  • Both lines 4 and 5 are not in the loop anymore.
  • It prints the same sum 10 times.
  • Is the print repeated now?
  • You get an error.
  • You have to have at least one statement in the body of a loop.
Next Section - What is a List?