Sign in

Intro to Computer Science

Unit 6

Loops

5 topics · 21 practice questions · Free responseNot yet reviewed

Notes

For and while loops

  • A for loop repeats for each item in a sequence. range(stop) starts at 0 and stops before stop; range(start, stop, step) sets the start and step.
  • A while loop repeats while its condition is True. Change a variable inside it or it becomes an infinite loop. break exits early; continue skips to the next pass.

Accumulators and nested loops

  • An accumulator builds a result (total += i). Start at 0 for sums and 1 for products. A counter adds 1 each time something happens.
  • In a nested loop the inner loop finishes all its passes for every pass of the outer loop. Total passes = outer x inner.

Tracing

  • Trace by writing a table of variable values for each pass. Watch for off-by-one errors with range and < versus <=.
total = 0
for n in range(1, 4):
total = total + n * n
print(total)

This prints 14 because 1 + 4 + 9 = 14.

Topics in this unit

Each topic has its own short notes and practice.

Practice

How many values does range(3, 8) produce?
What does for i in range(0, 10, 4): print(i) print?
What does n = 3; while n > 0: print(n); n = n - 1 print?
What is printed by total = 0, then for i in range(1, 6): total += i, then print(total)?
An outer loop runs 3 times and the inner loop runs 4 times, each printing one # on the same line. How many # characters are printed in total?
What is the effect of break inside a loop?

Free response

Write your answer first, then open the scoring guide.

Free-response question

Write loops for a small scoring program.

(a) Write a for loop that prints the even numbers from 2 to 10, inclusive.

Show the answer and scoring guide

for n in range(2, 11, 2):

print(n)

Check off the points you earned:

(b) Write code that uses an accumulator to add the numbers 1 through 100 and prints the sum. State the printed value.

Show the answer and scoring guide

total = 0

for n in range(1, 101):

total += n

print(total)

The sum printed is 5050.

Check off the points you earned:

(c) Trace this code and give the output: x = 2, then while x < 50: x = x * 3, then print(x).

Show the answer and scoring guide

x goes 2, 6, 18, 54. At 54 the condition 54 < 50 is False, so the loop stops. The output is 54.

Check off the points you earned: