A branch attaches a block of code to a condition. The block runs when the condition is True and is passed over when it is False, so the program takes one route out of several.
if opens the branch, elif adds another question, and else catches everything left over.:. Forgetting it is a SyntaxError, and Python points at the line where the colon should be.Python tests the conditions from the top. The first one that answers True wins: its block runs and every remaining condition in the chain is never checked. If none of them holds, the else block runs, and when there is no else the whole chain quietly does nothing.
Move the score and watch which line runs. The condition list on the right shows what Python asked, in the order it asked, and where it stopped asking.
One branch printed, and the conditions below it were never evaluated.
Replacing elif with a fresh if looks harmless and changes the result. A chain stops at the first match, while separate branches are all tested, so several of them can run for the same value.
In most languages a block is wrapped in braces and the layout is decoration. In Python the layout is the syntax: the indented lines are the block, and the first line back at the old margin is outside it.
Mixing tabs and spaces in the same file raises a TabError even when the lines look aligned, and a block with nothing indented under it needs pass to hold its place.
A while loop is a branch that comes back. Python tests the condition, runs the block when it holds, and then returns to the condition rather than moving on. The block repeats until the answer is False.
Drop the update and nothing about the condition ever changes, so Python keeps answering True and the block repeats without end. The program does not crash: it prints forever, or freezes with no output at all.
count = count + 1 under count > 0.Press Ctrl and C in a terminal to interrupt the program. In Jupyter or Colab, use the interrupt button on the toolbar. Before running any while loop, read the block once and name the line that will eventually make the condition False.
Press Step to advance one pass of the loop. The table records what the condition answered and the value of each variable after the block ran, which is the trace a programmer draws by hand when a loop misbehaves.
| Pass | n <= 5 | total | n | What happened |
|---|
Before the first pass, total is 0 and n is 1.
Two keywords interrupt the normal circuit from inside the block. They work in both kinds of loop, and each one skips a different amount of what is left.
| Word | Effect | Where the program lands |
|---|---|---|
| break | Leaves the loop at once | the first line after the loop |
| continue | Abandons the current pass | back at the condition |
while True pairs with break on purpose: the exit moves from the header down into the block, which suits a loop that ends on an event rather than on a count.
A for loop walks through a series of values. On every pass it puts the next value into the loop variable and runs the block, and it ends when the series is exhausted. The setup, the condition and the update are all folded into the header.
range builds the series of integer numbers, and minute is an ordinary variable that holds one of them at a time. The name is yours to choose: i is the habit for a plain counter, and a fuller name helps when the number means something.
The three forms differ only in how much you specify. What is left out takes its default value: counting starts at 0 and advances by 1.
| Call | Reads as | Produces |
|---|---|---|
| range(5) | up to 5 | 0 1 2 3 4 |
| range(2, 6) | from 2 up to 6 | 2 3 4 5 |
| range(0, 10, 3) | from 0 up to 10 in steps of 3 | 0 3 6 9 |
| range(5, 0, -1) | from 5 down to 0 | 5 4 3 2 1 |
| range(3, 3) | from 3 up to 3 | an empty series |
An empty range is not an error. The loop body simply never runs, and the program carries on with the line below.
Set the three arguments and read the series that comes out. Try a step larger than the distance, a negative step, and a start that already sits past the stop.
A for loop is not tied to numbers. It walks through anything Python can hand over one item at a time, and a string is the first such thing you already know how to write. Reaching for range here would make the same work harder: the counter would only serve to look each character up by its index.
Lists, tuples and dictionaries follow the same pattern, and they arrive in the next two guides.
Both loops repeat a block, so either one can be made to solve any repetition. The choice is about what the code says to a reader.
| Question | for | while |
|---|---|---|
| How many passes | Known before the loop starts | Depends on what happens inside |
| The counter | Handled by the header | Yours to create and advance |
| Risk of no exit | None, the series is finite | Real, the update can go missing |
| Typical use | Repeat n times, walk through data | Wait for input, repeat until a result is good enough |
Branches and loops combine by indenting one inside the other. Each level of nesting adds four more spaces, and the branch is evaluated afresh on every pass of the loop.
Six passes, six decisions. Nothing about the branch is remembered from one pass to the next.
The inner loop runs its full series for every single pass of the outer one, so the block at the centre runs as many times as the two counts multiplied together.
Three outer passes and three inner passes give nine numbers. The print() at the end sits at the outer level, so it runs three times rather than nine.
Read each fragment and trace what it prints before pressing Check. The answer button is there for when your trace and the verdict disagree.
elif and a stack of separate if lines answer differently, and choose between them.range and list the values it produces, including the empty case.