Conditionals
Learning Objectives
- You can write
if,if/else, andif/elif/elsestatements. - You can predict which branch will run for a given input.
- You understand that Python uses indentation to mark which lines belong to a branch.
- You can choose between several branches for a small classification task.
In the previous chapter, you learned to write expressions that evaluate to True or False. In this chapter, those expressions get put to work. An if statement tells the program to run some code only when a condition is true.
The Basic if
The simplest form has one condition and one branch.
minutes = 60
if minutes >= 60: print("That's a long session!")
print("Logged.")This program prints That's a long session! and then Logged. If minutes had been 30, the program would print only Logged. — the indented line would be skipped.
Two pieces of syntax are new here. The line that starts with if ends with a colon (:). And the line that runs only when the condition is true is indented by four spaces.
Conditionals and natural-language programming
0 / 5 points
Drag and drop the blocks to the “Program” area to create a program that prints “pass” when the input number is greater than 5 and “fail” otherwise. One of the blocks is an if block that allows adding another block inside its body.
Indentation Is the Syntax
In some languages, the code that belongs to an if is wrapped in curly braces or marked with keywords like then and end. In Python, the marker is indentation. The body of an if is the lines underneath it that are indented further than the if itself.
if minutes >= 60: print("That's a long session!") print("Great work.")
print("Logged.")Both indented lines belong to the if. They run together or not at all. The last line, which is not indented, is outside the if and always runs.
Python is strict about this. If your indentation is inconsistent, Python reports an IndentationError and refuses to run the program at all. Pick four spaces per level and stick with it. Most editors do this for you automatically once you press Enter after a line ending in a colon.
A common early mistake is to forget the colon:
if minutes >= 60 # missing colon! print("That's a long session!")Python responds with a SyntaxError, pointing roughly at the line with the missing colon. Read the error, add the colon, run again.
Fix the conditional shape
0 / 5 points
Arrange the blocks into a valid conditional program with correct colons and indentation.
else for the Alternative
Often you want one thing to happen if the condition is true and something else to happen otherwise. The else keyword handles that case.
minutes = 30
if minutes >= 60: print("That's a long session!")else: print("Nice short session.")Exactly one of the two branches runs. The condition is checked once; if it is true, the if branch runs; otherwise, the else branch runs. There is no “maybe both” and no “maybe neither”.
If-else with natural-language programming
0 / 5 points
Drag and drop the blocks to the “Program” area to create a program that prints “Your name starts with ‘A’” when the input name starts with the letter ‘A’, and “Your name does not start with ‘A’” otherwise. One of the blocks is an if-else block that allows adding blocks to the bodies of both if and else.
Note the syntax: else also ends with a colon, and its body is indented to the same level as the if’s body.
Session length message
0 / 10 points
Ask the user for a number of study minutes. Convert the answer to an integer.
If the minutes are at least 60, print Long session. Otherwise, print Short session.
Example input:
75Required output text:
Long session.Another example input:
20Required output text:
Short session.elif for Multiple Branches
Sometimes there are more than two cases. You want to classify a study session as short, medium, or long, or you want to give different responses to different input values.
Python uses elif (short for “else if”) for additional conditions:
minutes = 45
if minutes < 15: print("Short session -- better than nothing.")elif minutes <= 90: print("Solid session.")else: print("Long session -- make sure you took breaks.")The rules are:
- Python checks the conditions in order, from top to bottom.
- As soon as one of them is true, that branch runs.
- The remaining
elifandelseclauses are skipped.
So in the program above, if minutes is 45, Python first checks minutes < 15. That is false, so it moves on. It checks minutes <= 90. That is true, so Solid session. is printed, and the else is skipped.
You can have as many elif clauses as you need:
if minutes < 15: response = "Very short."elif minutes < 30: response = "Short."elif minutes < 60: response = "Medium."elif minutes < 120: response = "Long."else: response = "Very long."
print(response)This is a typical classification pattern. Each branch handles one range of values. The else at the end handles everything that did not match.
Choosing an elif branch
0 / 5 points
What does this code print when minutes is 30?
if minutes < 20: print("tiny")elif minutes < 45: print("short")else: print("long")Order Matters in elif Chains
Because Python checks conditions top to bottom and stops at the first match, the order of your branches matters. Look at this program:
if minutes < 60: print("Under an hour.")elif minutes < 30: print("Under half an hour.")If minutes is 20, the first condition is true, so Under an hour. is printed. The second branch, even though it also matches, is never reached. The “Under half an hour.” message is unreachable code: it can never run.
A useful habit when writing elif chains is to put the most specific conditions first and the most general ones last. For threshold-based classification, that usually means listing branches in either strictly increasing or strictly decreasing order.
Reachable branches
0 / 5 points
You want this program to print tiny for sessions under 15 minutes, short for sessions under 30 minutes, and longer otherwise.
Which order keeps every branch reachable?
What Happens When No Branch Matches?
When you write an if without an else, and the condition is false, nothing happens at all. The program just moves on.
if minutes >= 60: print("Long session!")
print("Logged.")If minutes is 30, this program prints only Logged. There is no error. There is no warning. The if simply did not apply.
This is fine when you only want extra behavior in one case. But it is also a quiet source of bugs. If you intended to handle two cases and only wrote one, the program will run without complaint and silently skip the case you forgot. When you write a chain of elifs, it is usually worth asking: “what if none of these match? Did I want that to be silent, or did I want an else?”
A useful default: when writing an
elifchain that classifies a value, finish it with anelse. Even if theelseonly prints “Unknown.”, you have made the gap visible rather than letting it sit in the dark.
Explain the missing else case
0 / 10 points
A program contains this code:
score = 40
if score >= 80: message = "strong"elif score >= 50: message = "practice"
print(message)Explain what happens when score is 40, why it happens, and one small change that would make the gap visible.
Your answer should include:
- whether each condition is true or false,
- whether
messagegets a value beforeprint(message), - the kind of error or failure this causes,
- and a concrete fallback branch that would handle low scores.
Boundaries Need Attention
Look at this classifier again:
if minutes < 15: print("Short.")elif minutes <= 90: print("Solid.")else: print("Long.")What happens when minutes is exactly 15? The first condition minutes < 15 is false (15 < 15 is False), so Python moves on. The second condition minutes <= 90 is true, so Solid. is printed.
What about minutes = 90? The first condition is false. The second condition 90 <= 90 is true, so Solid. is printed.
What about minutes = 91? Both < and <= are false, so Long. is printed.
These are called boundary values — the exact numbers at the edges of each range. They are also one of the most common places that branching code is subtly wrong. Did you mean < or <=? Did you mean to include 15 in “Short” or in “Solid”? It is worth pausing every time you write a chain like this and asking explicitly what should happen at each boundary.
You will return to this in Verifying Behavior and Finding the Edge Cases AI Misses, where it becomes a systematic check for AI-generated code as well as your own.
Boundary classifier
0 / 10 points
Ask the user for a number of study minutes. Convert the answer to an integer.
Classify the session with these exact boundaries:
Under 30 minutes.for values less than3030 to 90 minutes.for values from30through90, including both boundary valuesOver 90 minutes.for values greater than90
Example input:
90Required output text:
30 to 90 minutes.Common Pitfalls
A short list of things that trip people up at this stage:
- Missing colon.
if minutes >= 60(no:) is a syntax error. - Wrong indentation. Mixing tabs and spaces, or indenting by different amounts on different lines, gives
IndentationError. =instead of==.if minutes = 60:is a syntax error. You meantif minutes == 60:.- Branch order. As shown above, ordering
if minutes < 60beforeelif minutes < 30makes the second branch unreachable. - Forgetting
else. A silent gap where one case is not handled. Sometimes intentional, often not.
When something goes wrong, read the error message before assuming the worst. Python is usually quite specific about what it could not parse.
Fix FizzBuzz branch order
0 / 10 points
The starter code contains a faulty FizzBuzz program. It asks for a whole number and should print:
FizzBuzzwhen the number is divisible by both3and5,Fizzwhen the number is divisible by3but not by5,Buzzwhen the number is divisible by5but not by3,- the original number otherwise.
The bug is in the branch order: a broad condition comes before a more specific condition. Because Python uses the first true branch in an if / elif chain, the combined FizzBuzz case is not reached for numbers such as 15.
Fix the program by reordering or rewriting the conditions so every case can be reached.
Example input:
15Required output:
FizzBuzzAnother example input:
10Required output:
BuzzCheck Your Understanding
- In the following program, what is printed when
minutesis60?
if minutes < 60: print("Under an hour.")elif minutes < 90: print("Between one and one-and-a-half hours.")else: print("At least an hour and a half.")- Why is Python strict about indentation, and what error does it report when indentation is wrong?
- In an
if/elif/elsechain, can more than one branch run for the same input? Why or why not? - Why is finishing an
elifchain with anelseoften a good idea, even if theelseis short?
AI Study Aid
Create a chapter diagram
We're looking into to what extent AI-generated diagrams could help with studying.
Use this study aid to generate an AI-generated visual summary of the material you just studied.
Each diagram style emphasizes the content in a different way, so you can choose the focus
that feels most useful.
Using the diagram generator is voluntary and does not affect your course progress. We encourage
you to try it out and see if it helps, but it's totally up to you! Your answers help us understand
how to make better study aids in the future.