Week 4: Branches and Boolean Logic
🎯 Objectives
For three weeks your programs have run straight through: the same statements in the same order, whatever the user typed.
This week they learn to choose.
The syntax is the easy part of that — if, elif, and else take one class meeting.
What takes longer is the consequence. A program that chooses can be right about one input and wrong about another, so running it once no longer tells you whether it works. From this week on, "it printed the right answer" and "it is correct" are two different claims, and the second one has to be earned.
By the end of the week you should be able to:
- Trace and write conditional statements —
if,elif,else, and oneifnested inside another — and say which branch runs for a given input. - Predict the value of a boolean expression built from the comparison operators (
<,>,<=,>=,==,!=) and the logical operatorsand,or, andnot, including short-circuit behavior and operator precedence. - Identify which values Python treats as true or false in a boolean context.
- Use
help()to read the documentation of a built-in function.
Two quizzes to keep track of, and they are not the same kind of test
Quiz 1 is this week, on Wednesday or Thursday depending on your section, 30 minutes, on paper, no AI. It covers Weeks 2 and 3 — not this week's material. The Unit 1 review page is the study material for it, and last week's guide is where the rest of that advice lives.
Quiz 2 covers Weeks 4 and 5 and is two weeks away, and it is a computer quiz: you will write a working program in Thonny and submit it, without AI. That flips how this week is best studied. For Quiz 1 the computer was for checking your pencil work; for Quiz 2 the computer is the exam, so the practice that counts is writing and testing whole programs under time pressure. Reading about conditionals is not practice for that. Typing them is.
First, a five-minute self-check
Answer these before you look anything up, and no Shell. Nothing here is graded; the point is to find out which items on the menu below deserve your time.
- What does
7 > 3evaluate to, and what type is that value? - What does
not 3 > 7 and 2 > 1evaluate to? Which operator does Python apply first? - Which of these five values are false in a boolean context:
0,"","0",0.0,-1? - In a program, what is the difference between the line
x == 5and the linex = 5? - A program reads
if score > 90:and thenelif score > 80:. The score is95. Does theelifcondition get evaluated at all? nameis the empty string. Doesif name and name[0] == "A":raise anIndexError? Doesif name[0] == "A" and name:?- Write the condition for "the age is between 13 and 19, inclusive."
If items 2, 3, and 6 were comfortable, skip ahead to the two activities about testing. If they were not, they are what the first three activities are for.
📚 Study menu
Class covers three things this week: if/elif/else and help() on Monday, boolean expressions and the logical operators after Quiz 1 on Wednesday, and then truthiness, nested conditionals, short-circuiting, and Thonny's debugger on Friday.
This is a menu, not an assignment. Nobody does all of it, and you are not behind if you pick two items and do them properly. This week has a quiz in the middle of it, so the first item is short on purpose and the rest of the week is where the new material lives.
Get Quiz 1 behind you first
Quiz 1 is Wednesday or Thursday and it covers Weeks 2 and 3, so whatever is left of that preparation belongs at the start of this week rather than the end.
Spend half an hour on the Unit 1 review page, under quiz conditions: paper, pen, timer, nothing else open.
Then, for every question you got wrong, write one line saying why.
"I forgot / always makes a float" and "I ran out of time" are different problems with different fixes, and the only way to tell them apart is to look at your own wrong answers.
That is the whole item. Do not spend the week on it. The rest of this page is about material the quiz does not cover, and Quiz 2 arrives faster than it looks.
If you only have an hour
Some weeks that is all there is, so here is the order to spend it in — after the quiz, not before.
- Ten minutes. The self-check above, then the W3Schools Booleans page.
- Twenty minutes. Trace two of your own conditional programs on paper, then check yourself with the debugger.
- Twenty minutes. Write one practice program from scratch, timed, with no AI and no notes.
- Ten minutes. Count the branches in that program and find an input that reaches each one, plus the ones on the boundaries.
Everything else on this menu is worth doing. That is the order to do it in when the week gets away from you.
Read about it
All three books put conditionals in one chapter, which makes this an unusually easy week to read for. Pick one of these three and you have the week covered; the third is short enough to add as a skim on top of either of the others.
Python for Everybody — 4. Conditional Execution
- Sections 4.1 through 4.6, in order: boolean expressions, logical operators, conditional execution, alternative execution, chained conditionals, nested conditionals.
- Then 4.8, on short-circuit evaluation, which is the one section here that repays a second reading.
How to Think Like a Computer Scientist — 7. Selection
- Sections 7.1 through 7.7, which is the whole week in seven short sections.
- Section 7.3, on the precedence of operators, is the one the other book does not give you as clearly.
- Then 5.1 Modules and Getting Help for
help(), which is a two-minute read. - This book has CodeLens boxes that step through a program one line at a time, which is the best free substitute for the debugger if you want to trace before Friday.
W3Schools — the reference-style skim
- Python Booleans, which is the shortest good explanation of truthiness anywhere.
- Python If…Else, plus its Elif, Else, Logical Operators, and Nested If subpages.
- Python Operators, specifically the Comparison Operators and Logical Operators subpages.
Where to stop reading, and what to ignore
Skip PY4E 4.7, on try and except. Catching exceptions is a special topic in Week 14, it is not on Quiz 2, and reading it now mostly teaches you a way to hide errors you should be fixing.
Skip TCS 7.8, Boolean Functions. It needs functions, which are next week; come back to it then and it will read as a two-minute section instead of a hard one.
On W3Schools, skip the Shorthand If and Ternary Operator pages. They show one-line forms such as print("A") if x else print("B"). They are real Python, and this course writes the long form all semester, because the long form is the one you can trace, indent, and nest.
None of the three books cover Thonny's debugger, which is Friday's tool. That one you learn in class.
Trace it on paper, then step through it
A conditional program has one execution path per input, and reading one off the page is a different skill from writing the code in the first place. It is also the skill that makes debugging possible, so it is worth practicing deliberately even though Quiz 2 is at a keyboard.
Take a program with branches in it — steel.py or pet_age.py from this week's practice problems, or one from the reading — and pick an input.
On paper, without running anything, write the line numbers in the order Python will execute them, and beside each if and elif the condition and whether it came out True or False.
Then write the output.
Now check yourself, and this is where Friday's tool earns its place.
In Thonny, press Ctrl+F5 to run in debug mode, set a breakpoint on the first if, and step one line at a time, watching which lines light up and what the variables hold.
When your trace and the debugger disagree, the debugger is right, and the disagreement is the most useful thing you will find all week.
Two traps worth tracing on purpose, because both produce a program that runs and lies:
- A chain where a later
elifcan never be reached, because an earlier condition already caught everything it would have matched. Swap two branches of a working chain and trace it again. - A condition with no parentheses where
and,or, andnotdo not group the way you read them.notbinds tightest, thenand, thenor.
Find out what Python calls true
Two of this week's objectives are really about one question — what counts as true — and the Shell answers it faster than any book.
Open Thonny's Shell and wrap each of these in bool(), predicting the answer before you press Enter: 1, 0, -1, 0.0, "", " ", "0", "False".
Three of the eight surprise almost everybody.
Then write the rule you have just derived, in one sentence.
While you are in the Shell, do the same for the other objective that lives there:
help() prints the documentation for anything you hand it, and reading its first line — the signature, the part in parentheses — pays off for the rest of the course.
help(round) in particular tells you something about rounding that Week 2 never mentioned.
What you should be able to state without hesitating afterward:
0,0.0, and""are false; every other number and every non-empty string is true, including"0"and"False".if name:andif name != "":do the same thing for a string, and the first one is what you will read in other people's code.- In
A and B, Python never evaluatesBifAis false. InA or B, it never evaluatesBifAis true. - That is why
if name and name[0] == "A":is safe on an empty string andif name[0] == "A" and name:raisesIndexError. ==compares,=assigns, and Python will not let you use=in a condition — which is one of the few places it protects you from yourself.
Test every branch, not just the one you wrote
This is the new skill of the week and the one Quiz 2 is built to check, so if you only do one thing from this menu after the quiz, do this one.
Take any program you have written with branches in it and make a small table on paper: one row per branch, holding an input that reaches it and the output you expect. Filling that table in is how you find the branch you cannot reach, the branch two different inputs both land in, and the output line you never actually looked at.
Then add rows for the boundaries — the inputs sitting exactly on the edge between two branches.
If a rule says "12 and under," the row you need is 12, not 10; if it says "65 and over," the row is 65.
Off-by-one errors at a boundary are the most common bug in conditional code and the least likely to be caught by inputs you chose casually, because casual inputs are never near an edge.
Now run every row and compare against what you wrote down.
Working with somebody makes this much better. Trade programs with a classmate and try to find an input that breaks theirs while they try to break yours. Being handed a failing input by another person is more memorable than finding one yourself, and it is the closest thing to how software actually gets tested. No one to work with? Come back to your own program a day later and try to break it then. Studying together is encouraged all semester, but the quizzes and anything you submit for a grade are yours alone.
Write a program under quiz conditions
Quiz 2 gives you a problem you have not seen and 30 minutes to write, run, and submit a program that solves it. The only honest rehearsal for that is to do exactly that.
Pick a problem you have not already solved — the two Extra Challenges at the bottom of the practice page are there for this, and the grade calculator is about the right size — and set a timer for 25 minutes. Close your notes, close every AI tool, and open nothing but Thonny. Write it, run it on at least three inputs, and stop when the timer does.
Then look at what actually cost you the time.
Almost nobody runs out of time because they did not know how elif works; they run out because they started typing before they knew what the branches were, or a typo in an f-string took four minutes to find, or they never decided what should happen at a boundary and had to work it out twice.
Those are all fixable, and they are only visible under a clock.
Try an AI tutor
Conditionals are the first topic where AI can write your entire program from the specification, correctly, in about a second. That makes it the first week where using AI badly costs you something real, because Quiz 2 asks you to write the program.
Three prompts that keep the work on your side of the table:
"Write a Python program that uses
if/elif/else, then introduce exactly one bug into it: either an off-by-one error at a boundary or a logical operator that should be the other one. Show me the buggy version only. Do not tell me where the bug is or what kind it is. When I guess, tell me only whether I am right.""Give me a table of twelve boolean expressions using
and,or,not, and the comparison operators, with some parentheses missing so that precedence matters. Leave the Value column blank and do not fill it in. After I answer, grade me one row at a time and explain only the rows I got wrong.""Here is a program I wrote: [paste it]. Do not rewrite it and do not tell me whether it is correct. Instead, give me three input values that you think would be worth testing, and say for each one which branch you expect it to reach."
That third one is worth doing every week from here on. Asking an AI for test cases rather than for code makes you better at the thing the quiz measures, and it is the "test every branch" item above done as a conversation.
The skepticism to carry this week is about precedence: asked to explain not a == b or c, AI tools produce confident and occasionally wrong groupings.
Python is the authority on what Python does, so put the expression in the Shell and let it settle the argument.
✍️ Reflection
Instructions
Download the Week 4 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, and this week question 4 matters most, because it is the one that changes how you study for Quiz 2. A few sentences each is plenty. Be specific and be honest.
1. What did you do this week? (Check all that apply.)
- Worked the Unit 1 review page before Quiz 1
- Read the sections listed for one or more of the textbooks
- Traced a conditional program on paper and predicted which branch would run
- Stepped through a program with Thonny's debugger
- Drilled
bool()andhelp()in the Shell - Made a branch-and-input table for a program, including its boundaries
- Wrote a program from scratch under a timer, with no AI
- Traded programs with a classmate and tried to break each other's
- Asked an AI tutor to drill me or to suggest test cases
- 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. Now that you have taken Quiz 1, how do you think it went?
- Better than I expected
- About what I expected
- Worse than I expected
- I honestly have no idea
- I have not taken it yet and need to make it up
4. Name one thing about the way you studied for Quiz 1 that worked, and one thing that did not. Now that you have seen an actual quiz, this is the most useful judgment you can make all semester, and it is worth more than any single topic. Then say what you are going to do differently for Quiz 2, keeping in mind that Quiz 2 is on a computer: you will write and test a working program rather than read code on paper. If what worked for Quiz 1 was reading and predicting, say what the equivalent preparation is when the quiz hands you a keyboard.
5. Give one boolean expression or one branch that did not do what you expected this week. Write what you expected, what actually happened, and the rule you were using that turned out to be wrong. The wrong rule is the useful part. Then say which of this week's objectives feels shakiest — tracing branches, predicting boolean expressions, truthiness, or help() — and what you plan to do about it before Quiz 2.
6. What is one thing you want gone over in class? Be as specific as you can: "why x == "yes" or "y" is always true" is useful, and "conditionals" is not. Answer this even if you feel confident, by naming the thing you would least like to see on Quiz 2. 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 for this week is concrete: could you sit down right now, with no notes and nothing open but Thonny, and write a working program with three branches and a nested if in 25 minutes? If a video, article, or tutorial made something click, drop the link and one line on why it helped; we collect these to improve the study menu for future students.
8. Paste one or two programs you wrote outside of class this week. Pick the ones with the most branches in them, and if you found an input that broke one of your own programs, say what it was.