CSCI 127 Joy and Beauty of Data · Unit 1: Data types · on Exam 1
1.6 Iteration: for and while
Study notes for Iteration: for and while in CSCI 127 Joy and Beauty of Data at Montana State University: the big ideas, code you should know, a worked example, common mistakes and an exam tip. The same topic has endless practice questions and flashcards in StudyCat.
Big ideas
for x in something:repeats the body once per item: characters of a string, numbers fromrange(), later items of a list.range(n)is 0 to n−1;range(a, b)is a to b−1;range(a, b, step)can count by 2 or backwards with a negative step.- The accumulator pattern: start a total (or count, or string) before the loop and update it inside:
total += x. while condition:repeats as long as the condition is true. Something in the body must move toward making it false, or the loop never ends.breakleaves the loop early;continueskips to the next turn. Nested loops run the inner loop completely for each turn of the outer one.
Code you should know
range and accumulators
total = 0
for n in range(1, 11):
total += n
print("sum 1..10 =", total)
for k in range(10, 0, -3):
print(k, end=" ")
print()
count = 0
for n in range(2, 50, 2):
count += 1
print(count, "even numbers")Output
sum 1..10 = 55 10 7 4 1 24 even numbers
while with a sentinel
total = 0
entry = input("Number (blank to stop): ")
while entry != "":
total += float(entry)
entry = input("Number (blank to stop): ")
print("Total:", total)Output
Total: 12.5
Nested loops draw a grid
rows = 3
cols = 5
for r in range(rows):
line = ""
for c in range(cols):
if (r + c) % 2 == 0:
line += "#"
else:
line += "."
print(line)Output
#.#.# .#.#. #.#.#
Worked example
How many times does
print run, and what is the last value printed?i = 1
while i < 100:
print(i)
i = i * 3Show the solution
Five times: 1, 3, 9, 27, 81. After 81 comes 243, which is not below 100, so the loop stops and the last value printed is 81.
Common mistakes
- Off-by-one with
range:range(1, 10)stops at 9. - Resetting the accumulator inside the loop instead of before it.
- A
whileloop whose variable never changes (infinite loop). In the playground, press Stop. - Using the loop variable after the loop and expecting the count rather than the last item.
Exam tipTrace loops with a table: one column per variable, one row per turn. For nested loops, count the inner turns times the outer turns.
Keep going in StudyCat
StudyCat is free for Montana State students: an endless quizzer with worked explanations, one-question lessons, flashcards, exam prep checklists, the class calendar with every deadline, a grade calculator and a study board for CSCI 127.