3.06 Conditionals
Make decisions with if, elif, and else, and trace which branch runs.
- Reference Guide
- College Board Requirements
- Lesson Plan
- Code Examples
- A. Building a condition — a question that answers True or False
- Code Runner Challenge
- B. Example A — one condition, and the answer that isn’t there
- Code Runner Challenge
- Code Runner Challenge
- Popcorn Hack 1 — the silent failure
- Code Runner Challenge
- C. Example B — more than two answers, with
elif - Code Runner Challenge
- Popcorn Hack 2 — the chain in the wrong order
- Code Runner Challenge
- D. Combining two questions —
and,or,not - Code Runner Challenge
- E. The same decision in JavaScript
- Code Runner Challenge
- F. The same decision in College Board pseudocode
- Hacks & Practice Tasks
- References
Reference Guide
Comparisons — these are what make a condition
Each one evaluates to True or False, and nothing else.
| Operator | Question it asks | Example | Result |
|---|---|---|---|
== |
are these equal? | amount == 0 |
False when amount is 500 |
!= |
are these different? | sender != "mom" |
True when sender is “unknown” |
> < |
bigger / smaller? | amount > 100 |
True when amount is 500 |
>= <= |
bigger or equal / smaller or equal? | score >= 9 |
True when score is 9 |
in |
is this inside that? | "gift card" in message |
True when the words appear |
= and == are not the same thing. = stores a value. == asks a question. Mixing them up is the single most common error in this topic.
The shapes
| Shape | Outcomes | When to use it |
|---|---|---|
if alone |
1 answer, 2 outcomes | Almost never. One outcome is silent. |
if / else |
2 answers, 2 outcomes | A yes-or-no decision. |
if / elif / else |
3+ answers | Ranges or levels, ordered narrowest first. |
Boolean operators — from 3.5, used here
| Operator | True when | Example |
|---|---|---|
and |
both sides are True | asks_for_money and not known_contact |
or |
either side is True | has_link or asks_for_money |
not |
flips it | not known_contact |
Every command in this lesson, in all three languages
This is the table to keep open. Everything this lesson uses, side by side. Working versions of rows 8–15 are in section 5 under E. The same decision in JavaScript (a live runner you can press Run on) and F. The same decision in College Board pseudocode — not just listed here.
| What you want | Python | JavaScript | College Board pseudocode |
|---|---|---|---|
| Store a value | x = 5 |
let x = 5; |
x <- 5 |
| Is equal to | x == 5 |
x === 5 |
x = 5 |
| Is not equal to | x != 5 |
x !== 5 |
x NOT= 5 |
| Greater / less | x > 5, x < 5 |
x > 5, x < 5 |
x > 5, x < 5 |
| Greater or equal | x >= 5 |
x >= 5 |
x >= 5 |
| Is inside | "a" in text |
text.includes("a") |
not in the reference sheet |
| Booleans | True False |
true false |
true false |
| If | if x > 5: |
if (x > 5) { |
IF (x > 5) |
| Otherwise if | elif x > 3: |
} else if (x > 3) { |
nested ELSE + IF |
| Otherwise | else: |
} else { |
ELSE |
| Both true | a and b |
a && b |
a AND b |
| Either true | a or b |
a \|\| b |
a OR b |
| Flip it | not a |
!a |
NOT a |
| Show something | print(x) |
console.log(x) |
DISPLAY(x) |
| Show what is inside what | indentation | { } |
{ } |
| Comment | # note |
// note |
// note |
The three rows that catch people out.
= versus == flips meaning between Python and pseudocode. In Python, = stores and == asks. In College Board pseudocode, <- stores and = asks. So a pseudocode x = 5 is a question, and a Python x = 5 is an instruction. Same characters, opposite jobs.
Pseudocode has no elif. A chain of three or more answers is written as IF / ELSE blocks nested inside each other. Python’s elif is shorthand for exactly that structure, which is why an exam question can look deeply indented when the Python equivalent is flat. Section 5D shows the same four answers written both ways.
JavaScript’s === is the one to use. JavaScript also has ==, but it converts types before comparing, so "5" == 5 is true. Use ===, which does not.
College Board pseudocode connections
| Pseudocode | Python | Python example | When you reach for it |
|---|---|---|---|
IF (condition) |
if condition: |
if score >= 9: |
One thing to check, one thing to do |
IF / ELSE |
if: / else: |
if x: ... else: ... |
Exactly two answers, both written down |
IF inside ELSE |
elif |
elif score >= 6: |
Three or more answers in a range |
| Boolean expression | comparison | amount > 100 |
Building the condition in the first place |
AND / OR / NOT |
and / or / not |
a and not b |
One condition from two questions |
Mistakes this lesson is about
| Mistake | What it looks like | Fix |
|---|---|---|
if with no else |
Prints nothing, raises nothing, exits 0 | Give every condition both answers |
= instead of == |
SyntaxError, or a silently wrong condition |
= stores, == asks |
elif chain in the wrong order |
Runs, prints, and is wrong. Later branches unreachable | Order thresholds narrowest first |
| Comparing different types | TypeError: '>' not supported |
int("10") before comparing to a number |
College Board Requirements
AP CSP Big Idea 3, Topic 3.6 Conditionals. Learning objective AAP-2.H: express an algorithm that uses selection.
Essential knowledge for this topic covers:
- Algorithms can use selection to decide which statements run, based on a Boolean expression.
- An
IFstatement runs a block only when its condition istrue; anIF/ELSEstatement runs one block or the other, so exactly one of the two always runs. - A Boolean expression evaluates to
trueorfalseand is built from comparison and logical operators.
The counting method in this lesson is how we check that a selection structure actually covers what it claims to. College Board pseudocode for the full elif chain is in section 5.
Verify the exact wording and page numbers against your own copy of the CED before quoting it on an assessment. We are citing the objective, not a page.
Lesson Plan
Learning Objective
By the end of this lesson you can build a condition out of a comparison, give every condition all of its answers, and order an elif chain so that no branch is unreachable.
Success Criteria
- You can look at an expression like
amount > 100and say what it evaluates to before running it. - Every input to your conditional produces output. Nothing falls off the end.
- You can look at an
elifchain and say whether any branch can never run.
One rule for the whole lesson: a condition is a question that always comes back
TrueorFalse, and every question needs all of its answers written down.
One scenario for the whole lesson. Every example and hack on this page is the same program: the scam-message trainer from a community project for a seniors’ nonprofit. A message arrives and the trainer decides what to tell an older adult about it.
Open a notebook before we start. There are two Popcorn Hacks here and you do them while we teach. Copying each finished one into your own portfolio notebook is your job, not ours.
This lesson is one condition at a time. When two conditions need four different answers, that is nesting, and it is a separate topic.
How the lesson goes
We build one idea at a time, and you run code after each one.
- A condition is a question. Comparisons like
amount > 100produceTrueorFalse. That value is the condition. - Example A — an
ifwith noelse, and the output it does not produce. - Popcorn Hack 1 — you fix a conditional that is silent for half its inputs.
- Example B — an
elifchain with four answers, ordered highest threshold first. - Popcorn Hack 2 — you fix a chain whose order makes two of its branches unreachable.
and/or/not— combining two questions into one condition.- The same decision in JavaScript and College Board pseudocode.
- Homework Hack, which you do at home rather than here.
Transfer the Popcorn Hacks yourself. We are not collecting them here. Paste each finished one into your own portfolio notebook as you go — section 6 has the frontmatter.
Tech Talk
A condition is any expression that evaluates to True or False. That is the whole definition.
Most conditions are not handed to you as True or False already. You build them out of a comparison:
amount > 100 # a question about a number
"gift card" in text # a question about text
sender == "mom" # a question about equality
if runs a block only when the condition is True. else runs when it is False. elif asks another question, but only if every condition above it was False — which is the thing that makes order matter.
Why counting matters here. In most languages a missing case is just wrong. In Python it is wrong and silent: if x: with no else, and x false, prints nothing, raises nothing, exits 0.
The count. One condition has 2 outcomes, so it needs 2 answers. A chain with 3 thresholds has 4 outcomes, so it needs 4 answers. Count the outcomes on paper, count the prints in the code, and compare.
Code Examples
Each example is followed by the Popcorn Hack that checks it. Do the hack before we move on.
| Example | What it shows | |
|---|---|---|
| A | Building a condition | comparisons produce True / False |
| B | One condition, no else |
the silent missing answer |
| Popcorn Hack 1 | you fix it | |
| C | Four answers with elif |
ordering thresholds |
| Popcorn Hack 2 | you fix the order | |
| D | and / or / not |
one condition from two questions |
| E | The same decision in JavaScript | runnable, same four answers |
| F | The same decision in College Board pseudocode | exam form, no elif |
A. Building a condition — a question that answers True or False
Before any if, look at what a comparison actually produces. Every line below prints True or False and nothing else. That value is the condition.
3.6 - Comparisons make conditions. Every line prints True or False.
message = "URGENT: send $500 in gift cards today to unlock your account"
amount_requested = 500
known_contact = False
print("gift card" in message) # is that text inside the message?
print(amount_requested > 100) # is the number bigger?
print(amount_requested == 0) # is it exactly zero?
print(known_contact) # already a yes/no fact, no comparison needed
print(len(message) > 200) # is the message unusually long?
Code Runner Challenge
3.6 - Comparisons make conditions. Every line prints True or False.
View IPYNB Source
# CODE_RUNNER: 3.6 - Comparisons make conditions. Every line prints True or False.
message = "URGENT: send $500 in gift cards today to unlock your account"
amount_requested = 500
known_contact = False
print("gift card" in message) # is that text inside the message?
print(amount_requested > 100) # is the number bigger?
print(amount_requested == 0) # is it exactly zero?
print(known_contact) # already a yes/no fact, no comparison needed
print(len(message) > 200) # is the message unusually long?
Notice the fourth line. known_contact is already True or False, so it needs no comparison. The other four are built by comparing two things. Both kinds are conditions — anything that lands on True or False can go after if.
Watch == versus =. amount_requested == 0 asks a question and produces False. amount_requested = 0 would store zero and destroy the value.
B. Example A — one condition, and the answer that isn’t there
The trainer’s first version. If a message mentions gift cards, warn the user.
Run it before reading on.
3.6A - One condition: run it, what prints?
message = "Hi Mom, are we still on for Sunday?"
if "gift card" in message:
print("Careful - this message is asking for gift cards.")
Code Runner Challenge
3.6A - One condition: run it, what prints?
View IPYNB Source
# CODE_RUNNER: 3.6A - One condition: run it, what prints?
message = "Hi Mom, are we still on for Sunday?"
if "gift card" in message:
print("Careful - this message is asking for gift cards.")
No output. No error. Skimming past it, you would assume it worked.
One condition means 2 possible outcomes. Count the answers: there is 1. The other outcome falls off the end of the program and disappears — and a scam trainer that says nothing is worse than no trainer at all, because to the person reading it, silence looks exactly like “this message is fine.”
One else fixes the silence:
3.6A - One else: now every outcome gets an answer
message = "Hi Mom, are we still on for Sunday?"
# 1 condition -> 2 outcomes -> 2 answers
if "gift card" in message:
print("Careful - this message is asking for gift cards.")
else:
print("No gift card request in this message.")
Code Runner Challenge
3.6A - One else: now every outcome gets an answer
View IPYNB Source
# CODE_RUNNER: 3.6A - One else: now every outcome gets an answer
message = "Hi Mom, are we still on for Sunday?"
# 1 condition -> 2 outcomes -> 2 answers
if "gift card" in message:
print("Careful - this message is asking for gift cards.")
else:
print("No gift card request in this message.")
Popcorn Hack 1 — the silent failure
A different condition in the same trainer. This one checks the amount of money a message asks for. Someone wrote the case they were picturing and stopped.
Step 1. Run the cell below without changing anything. Answer in chat: what does it print, and is that an error or a bug?
Step 2. Fix it so both outcomes print, and add a count comment above the if in this form: # 1 condition -> 2 outcomes -> 2 answers
Step 3. Paste your fixed code in chat, then copy it into your own notebook.
3.6 Popcorn 1 - Run it first. Then make both outcomes print.
amount_requested = 0
if amount_requested > 100:
print("This message is asking for a large amount of money.")
Code Runner Challenge
3.6 Popcorn 1 - Run it first. Then make both outcomes print.
View IPYNB Source
# CODE_RUNNER: 3.6 Popcorn 1 - Run it first. Then make both outcomes print.
amount_requested = 0
if amount_requested > 100:
print("This message is asking for a large amount of money.")
C. Example B — more than two answers, with elif
Two answers is often not enough. Our trainer scores each message from 0 to 10 and gives advice that matches how bad it is.
Three thresholds means four outcomes, so we need four answers. Watch the order: highest threshold first.
3.6B - Four answers from one number, highest threshold first
risk_score = 9
# 3 thresholds -> 4 outcomes -> 4 answers
if risk_score >= 9:
print("Do not reply. This is almost certainly a scam.")
elif risk_score >= 6:
print("This looks risky. Check with someone you trust before replying.")
elif risk_score >= 3:
print("Be a little careful, but this is probably fine.")
else:
print("Nothing suspicious in this message.")
Code Runner Challenge
3.6B - Four answers from one number, highest threshold first
View IPYNB Source
# CODE_RUNNER: 3.6B - Four answers from one number, highest threshold first
risk_score = 9
# 3 thresholds -> 4 outcomes -> 4 answers
if risk_score >= 9:
print("Do not reply. This is almost certainly a scam.")
elif risk_score >= 6:
print("This looks risky. Check with someone you trust before replying.")
elif risk_score >= 3:
print("Be a little careful, but this is probably fine.")
else:
print("Nothing suspicious in this message.")
Count the answers
risk_score |
Which branch runs | What the trainer says |
|---|---|---|
| 9, 10 | if |
Do not reply |
| 6, 7, 8 | first elif |
Check with someone you trust |
| 3, 4, 5 | second elif |
Be a little careful |
| 0, 1, 2 | else |
Nothing suspicious |
Four outcomes, four answers. Every possible score from 0 to 10 lands somewhere, and the final else is what guarantees it — there is no score that falls off the end.
Why the order is what it is. elif only gets asked when everything above it was False. So by the time Python reaches risk_score >= 6, it already knows the score is under 9. That is why >= 6 means “6, 7 or 8” here and not “6 or anything above.” Each branch quietly inherits the failures of the ones above it.
Try it: change risk_score and re-run until you have seen all four answers.
Popcorn Hack 2 — the chain in the wrong order
Same four answers, same four thresholds, nothing missing. This one is not silent — every input prints something. It is still broken.
Step 1. Run it without changing anything. risk_score is 9, the worst score a message can get. Answer in chat: what does the trainer tell that person?
Step 2. Harder question: which branches in this code can never run, for any score at all? Name them.
Step 3. Fix the order, paste it in chat, and copy it into your own notebook.
This is the one to remember. Counting answers does not catch it — there are four answers for four outcomes. You have to check that each branch is reachable.
3.6 Popcorn 2 - Run it first. Then fix the order.
risk_score = 9
if risk_score >= 3:
print("Be a little careful, but this is probably fine.")
elif risk_score >= 6:
print("This looks risky. Check with someone you trust before replying.")
elif risk_score >= 9:
print("Do not reply. This is almost certainly a scam.")
else:
print("Nothing suspicious in this message.")
Code Runner Challenge
3.6 Popcorn 2 - Run it first. Then fix the order.
View IPYNB Source
# CODE_RUNNER: 3.6 Popcorn 2 - Run it first. Then fix the order.
risk_score = 9
if risk_score >= 3:
print("Be a little careful, but this is probably fine.")
elif risk_score >= 6:
print("This looks risky. Check with someone you trust before replying.")
elif risk_score >= 9:
print("Do not reply. This is almost certainly a scam.")
else:
print("Nothing suspicious in this message.")
D. Combining two questions — and, or, not
Briefly, because these belong to 3.5 Booleans. We use them here; that lesson is where they get taught properly.
They let you build one condition out of two. and needs both sides True, or needs either side, not flips one.
3.6C - and / or / not, used to build one condition
asks_for_money = True
known_contact = False
print(asks_for_money and known_contact) # both must be True
print(asks_for_money or known_contact) # either one is enough
print(not known_contact) # flips it
# 1 combined condition -> 2 outcomes -> 2 answers
if asks_for_money and not known_contact:
print("A stranger is asking you for money. Treat it as a scam.")
else:
print("Not a stranger asking for money.")
Code Runner Challenge
3.6C - and / or / not, used to build one condition
View IPYNB Source
# CODE_RUNNER: 3.6C - and / or / not, used to build one condition
asks_for_money = True
known_contact = False
print(asks_for_money and known_contact) # both must be True
print(asks_for_money or known_contact) # either one is enough
print(not known_contact) # flips it
# 1 combined condition -> 2 outcomes -> 2 answers
if asks_for_money and not known_contact:
print("A stranger is asking you for money. Treat it as a scam.")
else:
print("Not a stranger asking for money.")
The limit of and, and where this lesson stops. asks_for_money and not known_contact gives you exactly two answers: that one combination, and everything else. It cannot tell “only asks for money” from “only a stranger” from “neither.” When those need four different answers, you need a conditional inside a conditional — and that is 3.07 Nested Conditionals, not this lesson.
E. The same decision in JavaScript
Identical logic to Example B — same four answers, same order. Only the punctuation changes: braces instead of indentation, else if instead of elif.
3.6B JS - The same four answers in JavaScript
let riskScore = 9;
// 3 thresholds -> 4 outcomes -> 4 answers
if (riskScore >= 9) {
console.log("Do not reply. This is almost certainly a scam.");
} else if (riskScore >= 6) {
console.log("This looks risky. Check with someone you trust before replying.");
} else if (riskScore >= 3) {
console.log("Be a little careful, but this is probably fine.");
} else {
console.log("Nothing suspicious in this message.");
}
Code Runner Challenge
3.6B JS - The same four answers in JavaScript
View IPYNB Source
%%js
// CODE_RUNNER: 3.6B JS - The same four answers in JavaScript
let riskScore = 9;
// 3 thresholds -> 4 outcomes -> 4 answers
if (riskScore >= 9) {
console.log("Do not reply. This is almost certainly a scam.");
} else if (riskScore >= 6) {
console.log("This looks risky. Check with someone you trust before replying.");
} else if (riskScore >= 3) {
console.log("Be a little careful, but this is probably fine.");
} else {
console.log("Nothing suspicious in this message.");
}
F. The same decision in College Board pseudocode
This is the form the AP exam uses. <- is assignment, = is the equality test, DISPLAY is output, and braces group a block.
riskScore <- 9
IF (riskScore >= 9)
{
DISPLAY("Do not reply. This is almost certainly a scam.")
}
ELSE
{
IF (riskScore >= 6)
{
DISPLAY("This looks risky. Check with someone you trust before replying.")
}
ELSE
{
IF (riskScore >= 3)
{
DISPLAY("Be a little careful, but this is probably fine.")
}
ELSE
{
DISPLAY("Nothing suspicious in this message.")
}
}
}
Read the indentation. College Board pseudocode has no elif, so a chain of four answers is written as IF / ELSE boxes inside each other. That is the same structure Python’s elif is a shorthand for — which is worth knowing before you see it on the exam and assume it is something new.
What to notice across all three. Python uses indentation, JavaScript uses braces, pseudocode uses nested ELSE blocks. None of that changes the decision. Counting outcomes, counting answers, and checking each branch is reachable works identically in every one.
Hacks & Practice Tasks
Homework Hack — build the trainer’s scoring step
Do this at home, in your own notebook. There is no runner for it on this page on purpose — the two hacks above were the interactive part.
Right now risk_score is just handed to us. Your job is to compute it, then report on it.
Here is the starting point to copy into your notebook:
# CODE_RUNNER: 3.6 Homework - score a message, then advise on it
message = "URGENT: send gift cards now to unlock your account"
amount_requested = 500
known_contact = False
risk_score = 0
# TODO 1: add to risk_score using conditionals, one signal at a time
# TODO 2: report on the final score with an if / elif / else chain
# TODO 3: count comment in this form, with your real numbers:
# N thresholds -> M outcomes -> M answers
Your task:
- Score the message. Use a separate
iffor each signal, adding torisk_score: +4 if the message mentions gift cards, +3 if the amount asked for is over 100, +2 if the sender is not a known contact. Say in a comment why each of these does not need anelse. - Report the score with an
if/elif/elsechain of at least four answers, ordered so no branch is unreachable. - Add the count comment above the chain, in the form above, with your real numbers.
- Prove every branch is reachable. In a markdown cell, give one set of input values that reaches each answer. If you cannot find inputs for a branch, that branch is dead code — fix the order.
- Test the extremes. Run it with a completely clean message and with one that trips every signal. Both must print something sensible.
Stretch, not graded: your scoring uses if with no else on purpose, which is the exact thing Example A called a bug. Explain in one sentence why it is fine here and not there.
If the Run button says “Failed to fetch”
The Python runner is not running your code in the browser — it sends it to a server. Which server depends on where you are:
| You are viewing | It calls | If it fails |
|---|---|---|
| a published page | your deployed Flask backend | the backend server is down or unreachable |
localhost preview |
localhost:8587 |
your own backend is not running |
For the second one, start the backend from your backend repo with source venv/bin/activate;python main.py. Your portfolio folder has no main.py — running it there gives No such file or directory.
The JavaScript runner executes in the browser and calls neither server, so you can always check your logic there while the Python side is down.
References
College Board. AP Computer Science Principles course and exam description, Big Idea 3, Topic 3.6 Conditionals, learning objective AAP-2.H. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-principles-course-and-exam-description.pdf
College Board. AP CSP Exam Reference Sheet — IF / ELSE blocks, <- assignment, = equality, DISPLAY. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-principles-exam-reference-sheet.pdf
The Python Language Reference, section 8.1, “The if statement.” https://docs.python.org/3/reference/compound_stmts.html#the-if-statement
“It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true; then that suite is executed (and no other part of the
ifstatement is executed or evaluated). If all expressions are false, the suite of theelseclause, if present, is executed.”
Two phrases in there are this whole lesson. “one by one until one is found to be true” is why the order of an elif chain decides which branches can ever run. “if present” is why a missing else is silent rather than an error.
MDN Web Docs, “if…else.” https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else
Open Coding Society. 1.02 Variables and Data Types (CSA Unit 1).
Open Coding Society. 3.07 Nested Conditionals. </OCS-Kit-Pages/lessons/python/3-07-nested-conditionals/> — the next topic, and the lesson this one hands off to.