Vocabulary for this course

The terms the chapters assume, in plain words. You can open this from any chapter.

argument
A value you put inside the parentheses when you call a function, which the function then receives.
block
A group of lines that belong together under one opening line, such as the body of an if or a loop.
branch
A path a program can take when a condition sends it one way or another.
call site
The place in the code where a function is called, as opposed to where it is defined.
class
A template that bundles data with the code that works on it; each copy has its own values.
dictionary
A collection of key and value pairs, where a key is used to look up its value.
exception
An error that stops the normal flow of a program unless some code catches it.
function
A named piece of code that does one job and can be called whenever you need it.
function object
A function treated as a value, so it can be stored in a variable, passed to another function, or returned.
indentation
The spaces at the start of a line that show which block it belongs to.
integer
A whole number with no decimal point, such as 3, 0 or -12.
list
An ordered collection of values that you can grow, shrink and reach into by position.
parameter
A name in a function definition that stands for the value the caller will supply.
return value
The result a function hands back to the code that called it.
scope
The part of a program where a name can be used; a name made inside a function is not visible outside it.
traceback
The report Python prints when a program fails, listing the calls that led to the error.
variable
A name that refers to a value, so you can use that value again later or change it.

Python from the ground up

Loops and repetition

The same line, written once and run many times: for, range and while, and how to keep a loop from running forever.

Part 4 of 15

Beginner14 min readBack to Courses

Write it once, run it many times

A program that prints ten lines usually has no business containing ten print lines. A loop says the work once and lets Python do it for every value in turn — the line is written once, and the repetition happens inside the machine.

The loop below uses for: for each number in the range, put it in the name step and run the indented line. The indented line is the body, and it runs once per value, exactly as many times as there are values.

A loop over a range

for step in range(1, 6):
    print(f"Step {step}")

range says which numbers

range(1, 6) produces 1, 2, 3, 4 and 5 — the last number is not included. That is not a quirk to memorise so much as a rule to remember: the range stops before the end, which is why range(1, 6) gives five numbers rather than six.

range(5) is the lazy version: it counts from 0 up to (but not including) 5. When a loop runs one time too many or too few, the range is almost always where to look, and printing the loop variable once is enough to see it.

The whole times table

One line is printed and the rest would take nine more. Print the whole five times table, from 1 to 10, with a for loop over range(1, 11).

Output
Click "Run" to execute your code

while: repeat until something changes

while repeats as long as its question stays true. It is for loops whose length you cannot know in advance — keep asking until the tank is full, not for exactly ten pours.

Because nothing counts the turns for you, the thing the question asks about has to change inside the body. A while whose condition never becomes false runs until the page is closed, which is why the pattern deserves care rather than fear.

If a loop prints nothing, print the first value it is given. Seeing what the loop variable actually holds finds most loop mistakes in one line.

Carrying a total through the loop

Many loops do not just print; they build an answer as they go. The pattern is a name created before the loop and updated inside it: set total = 0, then add each value with total = total + value, or the shorter total += value.

The starting value matters. A total starts at 0 because adding to nothing leaves the first value intact; a product starts at 1 for the same reason. Create the name outside the loop, or every turn will reset it to zero and the last value will be all you have.

The loop variable outlives the loop

The loop variable is an ordinary name, created by the loop and left behind when it finishes. After for n in range(1, 4):, n is 3 — the last value it held.

That is handy for a final message, but risky if the loop might run zero times: the name would never be created at all. When the answer must exist after the loop, create it before the loop and let the body update it.

A block can run zero times

A loop is not a promise that the body runs. for n in range(1, 1): hands the body no values at all, and the program continues as if the loop were never written. That is correct behaviour, and it is the reason a name created inside the body may not exist afterwards.

The same is true of a while whose question is false on arrival. If the answer must exist after the loop, create it before the loop with a sensible starting value, then let the body improve it. A total of 0 is a real answer; a total that was never created is a NameError.

The body is a block like any other

Everything indented under the for line belongs to the body, including an if and its own indented lines. Python reads the shape of the spaces, so a nested block needs more space than the one around it, and a line that returns to the left margin has left the loop behind.

This is where most “it runs every time” bugs come from: a summary line indented one level too far is inside the loop and repeats on every turn. Move it left until it lines up with the for, and it runs once, after the last value.

Three loop mistakes: range(1, 5) stops at 4, so the end is exclusive; a while body that never changes its condition runs forever; and a line meant to run once after the loop is indented into the body and runs every turn.

Try these next

  • Total the numbers from 1 to 10 and print the result after the loop.
  • Print a running total beside each number, so the last line matches the final answer.
  • Change range(1, 11) to range(1, 12) and explain the difference before running it.

A total that grows

The loop adds each number but prints only the final result. Print the running total inside the loop as well, then extend the range to 10.

Output
Click "Run" to execute your code

Check what you learned

One question at a time. A wrong answer explains itself — take another go.

Part 1 of 5

What numbers does range(1, 4) give the loop?