Week 9: While Loops and Sets
Submit PA3 to Gradescope
If you don't submit to Gradescope and get a nonzero score, you will receive a reflection grade of no higher than 15/30 points.
🎯 Objectives
Every loop you have written so far knew how many times it would run before it started.
A while loop doesn't.
It keeps going as long as its condition is true, which makes it the loop for "ask again until the input is valid" and "roll again until you get a six".
That freedom comes with a new way to go wrong: a loop whose condition never becomes false runs forever.
The second idea this week is the set, a collection that holds each value once.
It answers "have I seen this one already?" with a single in, and that question comes up inside a lot of while loops.
By the end of the week you should be able to:
- Trace and write a
whileloop for a job where you don't know ahead of time how many times it will repeat: validating input, or repeating until a random event happens. - Point to the three parts of any loop, its initialization, condition, and update, and use them to explain why a loop does or doesn't end.
- Say when a
whileloop is the wrong tool and aforloop should do the job. - Construct a set, test membership with
in, and use a set to remove duplicates or keep track of what you have already seen.
Quiz 4 covers this week and next
Quiz 4 covers Weeks 9 and 10 and is done without AI. Your instructor will share the details. Whatever its format, the skill underneath is writing a loop that does its job and ends, so this week, write the loops, run them, break them on purpose, and fix them.
📚 Study menu
Class covered while loops for input validation, loops that wait for a random number, and sets.
Your PA3 Parts A and B use all three, so this menu is short: the PA is most of the week's practice.
Pick what you need.
If you only have an hour
- Twenty minutes. "Find the three parts, then break them," below, in Thonny.
- Ten minutes. "While or for?", on paper first.
- Thirty minutes. Your PA3 Part A or B. Before you run it, point to its three parts out loud.
Read about it
Pick one option.
Python for Everybody: 6. Loops and Iterations
- 6.1 Updating variables, 6.2 The while statement, and 6.3 Infinite loops.
- This book has nothing on sets, so add the W3Schools pages below for those.
W3Schools: the reference-style skim
- Python While Loops.
- Python Sets, with its Access Set Items and Add Set Items subpages.
A few things you can skip for now
Both books show two extra keywords, break and continue, that jump out of a loop or skip ahead in it (PY4E 6.4 is all about continue).
They're handy, but they hide the loop's condition, and this week is about getting the condition right, so leave them for later.
The W3Schools set pages keep going into joining sets and "frozensets". Stopping after "Add Set Items" gives you everything PA3 uses.
Find the three parts, then break them
Type each loop into Thonny. Before you run it, label its initialization, condition, and update with comments, and predict what it prints.
Then change n = 6 to n = 27, and to n = 1, and predict again.
import random
rolls = 1
die = random.randint(1, 6)
while die != 6:
die = random.randint(1, 6)
rolls += 1
print("Got a 6 after", rolls, "rolls")
Run this one five times. Why can't you predict its output, and what can you say for sure about it?
Each of these two never ends. Find out why by reading them, not by running them. Then run them anyway, stop each one with the red Stop button, and fix it.
Check your answers
The first loop prints 8 for 6, 111 for 27, and 0 for 1, because the condition is false before the first pass.
The dice loop prints a different count each run, but always at least 1, and the last roll is always a 6.
In the first broken loop, the update is not indented, so it is outside the loop and i stays 10.
In the second, i goes 1, 3, 5, 7, 9, 11, … and skips right over 10. Writing i < 10 instead fixes it.
The rules you should be able to state afterward:
- A loop ends only if something inside it can make the condition false. That something is the update.
- A condition that tests
!=is risky when the value can jump past the target;<is safer. - A
whileloop can run zero times, just like aforloop.
While or for?
On paper, decide which loop you would use for each job, and write one line saying why.
- Print every name in a list.
- Keep asking for a PIN until the user types exactly four digits.
- Add up the numbers from 1 to 100.
- Roll two dice until you get doubles.
- Count the vowels in a word.
- Double a savings balance each year until it passes $1,000, and count the years.
- Print a countdown from 10 to 1.
- Draw cards from a shuffled deck until you draw an ace.
Check your answers
for: 1, 3, 5, and 7. You know how many times before the loop starts: one per name, 100 numbers, one per letter, 10 lines.
while: 2, 4, 6, and 8. The number of tries, rolls, years, or cards depends on what happens inside the loop.
Number 6 is the subtle one. You could work the count out with math first, but the loop is how you find it.
The rule: if you can say how many times the loop runs before it starts, use for.
A while loop that counts its way through a list with an index does a for loop's job the long way, with an extra update to forget.
Watch a set fill up
On paper, trace this loop, writing down seen and repeats after every pass:
seen = set()
repeats = 0
for word in ["the", "cat", "the", "hat", "cat", "the"]:
if word in seen:
repeats += 1
else:
seen.add(word)
print(len(seen), repeats)
Then predict each of these in the Shell before you press Enter:
| Expression | Your prediction |
|---|---|
set("banana") |
|
len(set([3, 1, 3, 2, 1])) |
|
type({}) |
|
{1, 2} == {2, 1} |
|
{"a", "b"}[0] |
Check your answers
The loop prints 3 3: seen ends as {"the", "cat", "hat"}, and three words were repeats.
set("banana") has three letters, b, a, and n, in whatever order Python shows.
The len is 3. {} is an empty dictionary, so an empty set is set().
Two sets with the same items are equal, in any order. And a set has no positions, so [0] is a TypeError.
What this should leave you with:
- A set never holds the same value twice, so adding a value it already has changes nothing.
- A set has no order and no index. Use it to answer
in, not to remember what came first. - That's why PA3's
sign_upandaskkeep a list for the order and a set for "seen it already".
Try an AI tutor
AI is a good drill partner for loops, as long as it doesn't hand you the code.
It also likes break, while True:, and comprehensions, none of which PA3 needs, so say so up front.
"I am a CS1 student who knows
forloops,whileloops, lists, dictionaries, and sets withaddandin. I don't knowbreak,while True, or comprehensions. Give me a shortwhileloop with a bug that makes it run forever, and don't tell me the bug. When I answer, tell me only whether I found it.""Describe six programming jobs in one line each, and don't say which kind of loop each needs. I will say
whileorforand why, and you tell me where you disagree."
The thing to be skeptical about this week is random code.
A program that uses random can pass every run you try and still be wrong on the run you didn't.
Ask yourself what the loop guarantees, not only what it printed this time.
✍️ Reflection
Instructions
Download the Week 9 reflection template, type your answers into it, and submit the completed document.
The first three questions are quick; the short answers are the ones that matter. Question 4 is about how you tested your PA3 Parts A and B, so answer it after you submit. A few sentences each is plenty. Be specific and be honest.
Submit PA3 to Gradescope
If you don't submit to Gradescope and get a nonzero score, you will receive a reflection grade of no higher than 15/30 points.
1. What did you do this week? (Check all that apply.)
- Read the sections listed for one of the textbooks
- Labeled and broke the loops in "Find the three parts"
- Sorted the jobs in "While or for?"
- Traced a set filling up on paper
- Worked on PA3 Part A or B
- Asked an AI tutor to drill me
- Something else (tell us in the short answers)
2. Roughly how much time did you spend on CS 149 outside of class this week?
- Under 1 hour
- 1–2 hours
- 3–4 hours
- 5–6 hours
- 7+ hours
3. How do while loops feel so far?
- I can write one and say why it ends
- I can write one, but I'm not always sure it will end
- I can read one, but writing one from scratch is hard
- I'm still not sure when to use
whileinstead offor
4. How did you test your program? Before you submitted PA3 Parts A and B to Gradescope, what calls or inputs did you try, and what could each one have caught? For Part A, how did you convince yourself the loop would end, even when no name or question is left?
5. Give one loop this week that did not do what you expected. It could be one that never ended, ended too soon, or ran a different number of times. Name its initialization, condition, and update, and say which one was wrong and what rule you were using that turned out to be wrong.
6. What is one thing you want gone over in class? Be as specific as you can: "how ask knows to stop after the right answer" is useful, and "while loops" is not. Class time gets spent on whatever shows up most often in these answers.
7. Did you use an AI tool this week, and did it build your understanding or replace it? The honest test: could you write PA3's Part B loop again on a blank page, and point to its three parts? If a video, article, or tutorial made something click, drop the link and one line on why it helped.
8. Paste your PA3 code, Parts A and B at least. If labeling the three parts of one of your loops showed you something, say what.