StudyCatLearn / Practice / Excel
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

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 * 3
Show 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

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.