Notes
For and while loops
- A
forloop repeats for each item in a sequence.range(stop)starts at 0 and stops beforestop;range(start, stop, step)sets the start and step. - A
whileloop repeats while its condition is True. Change a variable inside it or it becomes an infinite loop.breakexits early;continueskips 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
rangeand<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
range(3, 8) produce?It produces 3, 4, 5, 6, 7, which is 5 values.
for i in range(0, 10, 4): print(i) print?Counting by 4 from 0: 0, 4, 8, then 12 is not less than 10.
n = 3; while n > 0: print(n); n = n - 1 print?n prints 3, 2, 1 and the loop stops when n reaches 0.
total = 0, then for i in range(1, 6): total += i, then print(total)?1 + 2 + 3 + 4 + 5 = 15.
# on the same line. How many # characters are printed in total?3 x 4 = 12.
break inside a loop?break ends the loop; continue skips to the next pass.
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: