Search the courses, subjects, tracks, games and features, or jump straight to a page.
Learn it your way
A short class with Sarah and her students. The other ways are under More.
Sign up free to listen. Transcripts are free to read.
Let's pull the chapter together. What does control flow let a program do?
Choose which lines to run, depending on whether a condition is True or False.
Right. In an if/elif/else chain, how many branches can run?
Only one. Python checks the conditions from the top, runs the first True one and skips the rest.
Good. So with score = 95, what goes wrong if the first test is if score >= 60:?
That test is already True, so the program prints C and never reaches the test for A.
Exactly. Put the strictest condition first and let else catch whatever is left.
Python has no braces, so how does it know which lines belong to an if?
From the indentation. The if line ends with a colon, and the lines under it are indented, usually by four spaces.
And what happens if you forget to indent the print under an if?
Python raises an IndentationError before the program even starts.
Yes. Two other classics are writing if x = 5: instead of if x == 5: and forgetting the colon. Both are syntax errors.
So a single = stores a value, and == compares two values.
Exactly. And the sneakiest mistake raises no error at all: conditions in the wrong order. So test every branch with different values.
Last idea: nesting. When would you put one if inside another?
When the second question only matters if the first answer is yes, like checking for a voter ID only after we know the person is 18 or older.
Good. If each answer needs its own message, nesting is clear. But if you only care whether both are true, what could you write instead?
if age >= 18 and has_voter_id: on one line.
Exactly. Fewer levels of indentation make code easier to read, so use nesting when each level needs its own response.
And else always pairs with the if at the same indentation level, right?
Right. Line up each else with its own if, and Python will match them correctly.
An expression that is either True or False, often built with comparison operators and combined with and, or and not.
Runs its block only when its condition is True.
elif tests the next condition only if all earlier ones were False, and else catches every remaining case.
In one if/elif/else chain only the first True branch runs, so order conditions from strictest to loosest.
A colon ends each decision line and consistent indentation (four spaces) marks the block; a missing indent is an IndentationError.
An if inside another if handles follow-up questions, and the and operator can often flatten them into a single test.
Decide whether a number is positive, negative or zero (the first Try It Yourself task):
number = -7
if number > 0:
print(number, "is positive")
elif number < 0:
print(number, "is negative")
else:
print(number, "is zero")See why the order of conditions matters, using the same score in two chains:
score = 95
if score >= 60:
print("Wrong order gives: C")
elif score >= 75:
print("Wrong order gives: B")
elif score >= 90:
print("Wrong order gives: A")
if score >= 90:
print("Right order gives: A")
elif score >= 75:
print("Right order gives: B")
elif score >= 60:
print("Right order gives: C")
else:
print("Right order gives: D")Check voting eligibility with a nested condition, then with a single condition joined by and:
age = 20
has_voter_id = True
if age >= 18:
if has_voter_id:
print("Nested check: you can vote.")
else:
print("Nested check: bring your voter ID.")
else:
print("Nested check: you are too young to vote.")
if age >= 18 and has_voter_id:
print("Combined check: you can vote.")
else:
print("Combined check: you cannot vote yet.")Compare three separate if statements with one if/elif chain:
temperature = 35
print("Three separate if statements:")
if temperature > 30:
print("It is hot")
if temperature > 20:
print("It is warm")
if temperature > 10:
print("It is mild")
print("One if/elif chain:")
if temperature > 30:
print("It is hot")
elif temperature > 20:
print("It is warm")
elif temperature > 10:
print("It is mild")Colon at the end, indent below; the first true branch wins, and on you go.
At the cinema, the usher first checks Rohan's ticket and only then checks his age for the late show. Every visitor is sent through exactly one door, and anyone who matches no door is sent to the help desk, just like else.
I Eat Eggs - If tests first, Elif tests next, Else catches the rest.
C.I.F. - Colon at the end of the line, Indent the block, First true branch wins.
Term
How many branches of an if/elif/else chain can run?
Click to flip
Term
When is an elif condition checked?
Click to flip
Term
Does else have a condition?
Click to flip
Term
How does Python know which lines belong to an if block?
Click to flip
Term
What is wrong with `if x = 5:`?
Click to flip
Term
When is a nested condition useful?
Click to flip
The order in which a program's statements run, changed by decisions such as if, elif and else.
An expression that evaluates to True or False, such as age >= 18.
A statement that runs its indented block only when its condition is True.
Short for "else if"; it tests another condition only when every condition above it was False.
The final part of a chain, with no condition of its own, that runs when no earlier condition was True.
The group of indented lines that belongs to an if, elif or else.
The error Python raises when a block is missing its indentation or is indented inconsistently.
An if statement placed inside the block of another if, elif or else.
This summary brings Chapter 4 together: how if, elif and else let a program choose which code to run, why indentation defines each block, and how nested conditions handle decisions that depend on more than one fact.
Control flow lets a program decide which statements to run based on conditions that are either True or False. An if block runs only when its condition is True, elif tests further conditions in order when every earlier one was False, and else catches all remaining cases. In a single chain, only the first branch whose condition is True runs, so the order of the conditions matters. Python marks each block with a colon and consistent indentation, which makes a missing indent an error rather than a matter of style. Nested conditions place one decision inside another, and the and operator can often flatten them into one test. This summary reviews each statement, highlights the most common mistakes and works through complete examples.
Without control flow, a program runs every line from top to bottom, every time. Control flow lets it react to its data, so the same grading program prints "A" for one student and "C" for another. Every decision rests on a condition, an expression that is either True or False. Conditions are usually built from the comparison operators of Chapter 3 (==, !=, >, <, >=, <=) and can be combined with and, or and not.
An if/elif/else chain runs at most one branch. Python tests the conditions from top to bottom, runs the first one that is True and skips the rest of the chain. With an else at the end, exactly one branch always runs.
Because the first True condition wins, put the strictest test first. With score = 95, a chain that starts with if score >= 60: prints "C" and never reaches the test for "A". Starting with if score >= 90: gives the right grade. This kind of bug raises no error at all, so test every branch, including boundary values such as exactly 60 or exactly 90.
Every if, elif and else line ends with a colon, and the lines that belong to it are indented by the same amount, normally four spaces. Python uses this indentation, not braces, to know where a block starts and ends. A missing indent after a colon raises an IndentationError, and a line indented by mistake can silently move into or out of a block, so it runs when it shouldn't (or doesn't run when it should).
You can put an if inside another if when a second question only makes sense after the first one is answered, such as checking for a voter ID only after confirming that the person is at least 18. Each level adds four more spaces of indentation. When the inner branches don't need their own messages, and often replaces the nesting: if age >= 18 and has_voter_id: asks both questions at once.
The program below assigns a grade with an if/elif/else chain and then uses a nested condition to decide whether the student qualifies for a certificate.
marks = 82
attendance = 90
if marks >= 90:
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
else:
grade = "D"
print("Marks:", marks, "Grade:", grade)
if marks >= 60:
if attendance >= 75:
print("Certificate awarded.")
else:
print("Passed, but attendance is too low for a certificate.")
else:
print("No certificate: the marks are below 60.")With 82 marks the first test is False and the second is True, so the grade is B and the remaining tests are skipped. Because the marks are at least 60 and the attendance is at least 75, the program also prints Certificate awarded.