This lesson defines a program as a sequence of instructions, names the five kinds of instruction every language provides, and gets a first program running at the Python prompt.
Subject: Python · 65 slides · code lesson
Open the interactive version of this deck
Title
Python · Chapter 1 — The way of the program
§1.1-1.3, pp. 1-3
Objectives
Five things, each one you can check yourself at an interpreter prompt.
print('Hello, World!'), and say what every character in it is for.Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 1-3 — the pages these objectives are drawn from
Warm-up
You have used dozens of programs today without once asking what one is. Start there.
Discussion prompt
Think of any app you used in the last hour. Name one moment where it must have GOT some data from somewhere, one moment where it must have SHOWN you something, and one moment where it must have DECIDED between two things. Write the three moments down in plain English.
Hint: You are not guessing at the code. You are describing what the program obviously had to do.
Answer:
Almost everyone finds all three without difficulty. A messaging app gets your typed text, shows the conversation, and decides whether to mark a message as read.
That is not a coincidence, and it is not specific to messaging apps. Those three moments are three of the five kinds of instruction the whole of programming is built from — and this lesson names all five.
Hold on to your three examples. You will sort them into the official categories later in this lesson.
Concept
A program is a sequence of instructions that specifies how to perform a computation. That sentence is the whole definition, and both halves of it do work.
program — A sequence of instructions that specifies how to perform a computation.
The word computation is broader than it sounds. It covers solving an equation, but equally searching and replacing text in a document, processing an image, or playing a video. And the word sequence is the half people skip: the instructions happen in an order, and changing the order changes the program.
Figure (svg): A three-stage diagram showing data entering a program, instructions being carried out in order inside it, and a result leaving it
Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 1-1 — the definition, in the book's own words
Section
Section 1
Concept
A recipe that says bake for 40 minutes and stir in the eggs is a different recipe depending on which line comes first. A program is the same: the instructions are carried out one after another, top to bottom, and each one runs against whatever the ones before it left behind.
print('Ready?')
print('Set.')
print('Go!')| Line | What runs | What is on the screen after it |
|---|---|---|
| 1 | print('Ready?') | Ready? |
| 2 | print('Set.') | Ready? Set. |
| 3 | print('Go!') | Ready? Set. Go! |
Nothing here is clever. That is the point: you can predict what this program does with no knowledge except the lines happen in order, and that single rule will carry you a very long way.
Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 1-1
Picture it
The interpreter keeps its place. At any instant exactly one line is the current one.
Figure (svg): A ladder of three rungs, one per line of a three-line program, with an arrow dropping from each rung to the next and the screen contents written beside each
Every new construct in this book is a way of changing which rung the arrow goes to next. That is genuinely all they are.
Worked example
Write down what you think appears on the screen, in order, before you advance.
print('first')
print('second')
print('third')
print('first')| Line | What runs | Screen so far (comma-separated) |
|---|---|---|
| 1 | print('first') | first |
| 2 | print('second') | first, second |
| 3 | print('third') | first, second, third |
| 4 | print('first') | first, second, third, first |
Start at line 1 and run it.
Why: A script runs from the top. There is no other entry point to look for.
Run each following line in turn, without skipping any.
Why: Nothing in this program changes which line comes next, so the order on the page is the order of execution.
Notice that line 4 is identical to line 1.
Why: Being identical does not make it the same instruction. It runs at a different time, and it produces a fourth line of output.
Figure (svg): The state of the program after each line of Worked example predict the output of a four-line program, drawn as a ladder with one rung per traced line
The screen shows four lines: first, second, third, first. The word first appears twice because the instruction to print it appears twice.
Verify: Count the print statements, then count the lines of output.
Why: There are four print statements and four lines of output. In a program with no repetition and no conditions, those two counts must match, and checking them catches a dropped or duplicated line immediately.
Prediction
You have just seen a swap that changed everything. Now decide whether that always happens.
Predict first
If you swap two lines of a program, must the output change?
Correct: No — it depends on what the two lines are. Swapping two identical print statements changes nothing, and neither does swapping two lines that do not affect each other.
Why: Order being part of a program's meaning says that a swap MAY change the result, not that it must. Swap the two lines print('a') and print('a') and the output is identical. The honest version of the rule is: you may not assume a swap is safe, so you must check. That is a much more useful rule than either extreme, and it is the habit that will keep you out of trouble when the lines start affecting each other in chapter 2.
Worked example
This is the same program as before with lines 1 and 3 swapped. Decide whether the output changes.
print('Go!')
print('Set.')
print('Ready?')| Line | What runs | What is on the screen after it |
|---|---|---|
| 1 | print('Go!') | Go! |
| 2 | print('Set.') | Go! Set. |
| 3 | print('Ready?') | Go! Set. Ready? |
Compare the set of instructions with the earlier program.
Why: It is exactly the same set: three print statements, with the same three pieces of text.
Run the lines in the order they now appear.
Why: The interpreter does not know or care that these lines once appeared in another order. It reads what is in front of it.
Compare the output with the earlier program's output.
Why: Same instructions, different order, different result — which is what it means to say a program is a sequence rather than a set.
Figure (svg): Two columns of three lines each, showing the same three print statements in two different orders with their two different outputs underneath
The output is Go! then Set. then Ready? — the reverse of before. The instructions are identical; only their order changed, and that was enough to change what the program does.
Verify: Ask whether any single line, read on its own, behaves differently than it did before.
Why: No line behaves differently in isolation. The difference lives entirely in the ordering, which proves the order is part of the program's meaning and not merely part of its layout.
Trap
Asked to write a program that greets the user three times, a beginner writes:
greet the user three times
Describe the outcome you want
Why: This is how you would brief a person, and people are extremely good at filling in the unstated steps.
Python fills in nothing. It has no notion of greet, no notion of the user, and no way to decide what three times should look like.
A program has to say which instructions, in which order:
Name the exact instruction that produces one greeting
Why: print is an instruction Python already has. Greeting is not.
Write that instruction once for each greeting you want
Why: Repetition has a shorter form, which arrives in chapter 7. Until then, writing it three times is not a cheat — it is a correct program.
Three print statements, one after another, is a complete and correct answer. The vaguer sentence was not a program at all; it was a description of one.
This is the single most common way a first program fails to exist: the writer described the destination rather than the route.
Sorting
Only one of these two things can be typed into Python and run.
Sort into buckets
Sort each line into the box it belongs in.
Socratic
The interpreter has to start somewhere, and where it starts is not an arbitrary choice.
Discussion prompt
Suppose Python started executing a script at whichever line it felt like, rather than at the top. Describe one specific thing that would immediately stop working, using the four-line program from earlier as your example.
Hint: Think about what the fourth line of that program depended on.
Answer:
The four-line program printed first, second, third, first. If execution could start at line 3, the output would begin with third — and the word 'first' would no longer mean what it says.
More seriously: from chapter 2 onward, lines will depend on values that earlier lines created. A line that uses a name before any line has given that name a value is an error, and starting in the middle would produce those errors constantly.
Top to bottom is not a stylistic convention. It is the guarantee that lets you reason about a program by reading it in the order it is written.
Two truths and a lie
Two of these follow from the definition. One does not.
Eliminate the wrong options
Three claims about programs. Rule out the two that are true, and keep the lie.
Survives elimination: C
Why: A and B are the two halves of the book's definition: a program is a SEQUENCE (so there is a definite order) of instructions that specifies HOW to perform a computation (so it is a method, not a wish). C contradicts the first half — if the same instructions in any order always gave the same result, the word sequence would be doing no work at all. The counterexample is the one you have already run.
Section
Section 2
Concept
The details look different in different languages, but a few basic instructions appear in just about every language. Here they are, and there are five of them.
Believe it or not, that is pretty much all there is to it. Every program you have ever used, no matter how complicated, is made of instructions that look pretty much like these.
Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 1-2 — the five categories, quoted from the book
Picture it
This is not a summary of chapter 1. It is a summary of the entire book, and of every program you will ever read.
Figure (svg): Five labelled boxes in a row, named input, math, conditional execution, repetition and output, with arrows between them
When a program confuses you later in the course, the first question worth asking is which of these five each line is. It is a surprisingly effective question.
Worked example
You have not met most of this syntax yet. Label the lines anyway — the categories are readable long before the code is.
name = input('What is your name? ')
letters = len(name)
if letters > 8:
print('That is a long name.')
else:
print('Nice and short.')| Line | What it does | Which of the five |
|---|---|---|
| 1 | ask the keyboard for text | input |
| 2 | count the letters | math |
| 3 | compare the count with 8 | conditional execution |
| 4 | display one message | output |
| 6 | display the other message | output |
Read line 1 for what it fetches, not for its syntax.
Why: The word input is doing exactly what the category says: data arrives from the keyboard.
Read line 2 as a computation.
Why: Counting is arithmetic. It belongs in the math category even though no plus sign appears.
Read line 3 as a question with two answers.
Why: That is the definition of conditional execution: check a condition, then run the appropriate code.
Read lines 4 and 6 as the same category as each other.
Why: Both display something on the screen. Which one runs is decided by line 3; what kind of instruction they are is not in doubt.
Figure (svg): A flow chart with a start box, two action boxes, a diamond testing whether the name is longer than eight letters, and two output boxes on the two branches
Four of the five categories appear: input, math, conditional execution and output. Only repetition is missing — nothing in this program happens more than once.
Verify: Check the claim about repetition by counting how many times each line can run.
Why: Each line runs at most once, and lines 4 and 6 are mutually exclusive. Nothing loops back, so the repetition category genuinely is absent — the check confirms the answer rather than restating it.
Definition probe
Use your own three examples from the warm-up if they fit better than these.
Sort into buckets
Each of these is something a program you have used does. Which category is it?
Worked example
The previous program used four of the five. Decide what the smallest honest change is that brings in the fifth.
name = input('What is your name? ')
for letter in name:
print(letter)| Line | What it does | Which of the five |
|---|---|---|
| 1 | ask the keyboard for text | input |
| 2 | start a loop over the letters | repetition |
| 3 | display one letter | output (runs once per letter) |
Identify what has to happen more than once.
Why: One print per letter. The number of times is not known when the program is written, which is precisely why a loop is needed rather than more print statements.
Notice that line 3 appears once but runs many times.
Why: This is the first place where the count of lines and the count of actions come apart. It is the whole reason repetition is its own category.
Check which categories are now present.
Why: Input on line 1, repetition on line 2, output on line 3. Math and conditional execution have dropped out.
Figure (svg): The state of the program after each line of Worked example which category is missing, and what would add it , drawn as a ladder with one rung per traced line
A loop adds repetition. Line 3 is written once and runs once per letter, so a five-letter name produces five lines of output from a three-line program.
Verify: Run the count check from the first worked example and watch it fail.
Why: Three lines of program, five lines of output — the counts no longer match. That check was only ever valid for programs with no repetition and no conditions, and seeing it break here is the clearest possible evidence that repetition is a genuinely different kind of instruction.
Trap
A student opens a real application's source code, sees thousands of lines and dozens of unfamiliar words, and concludes that the five categories were a simplification for beginners.
Assume complexity means new kinds of instruction
Why: Every unfamiliar word looks like it might be a sixth category.
The conclusion feels reasonable and is wrong. The unfamiliar words are names of functions somebody wrote — combinations of the five, not additions to them.
Complexity comes from combination and from scale, not from new categories.
Treat every unfamiliar name as a package of the five
Why: Somebody wrote it, out of input, output, math, conditions and repetition, exactly as you are about to.
Ask which of the five the line ultimately performs
Why: You will not always be able to tell from the outside, and that is the point of packaging: you use the package without re-deriving its contents.
Chapter 3 makes this concrete by having you write such a package yourself. From then on your own programs will contain words that were not in Python either.
So: thousands of lines, five kinds of instruction, and an unlimited supply of names for combinations of them.
Matching
You do not need to understand the right-hand column yet. You need to know that it exists and where it is going.
Match the pairs
Why: This is the map of the first half of the book. Each category gets its own chapter or two, in roughly this order, and the reason the order looks like this is that output and math need nothing to be useful, while conditions and repetition need values to be conditional and repetitive about. You are starting with the two that stand alone.
Estimation
Estimate first, then justify. There is a defensible answer.
Predict first
A basic calculator app — digits, four operations, an equals key. How many of the five categories does it need?
Correct: All five, once you look closely at what pressing a key has to do.
Why: Input is obvious (key presses) and so are output (the display) and math (the operations). Conditional execution appears the moment the program must behave differently for a digit than for an operator, and again for division by zero. Repetition appears because the app must wait for and handle key press after key press, indefinitely — a loop that never ends until you close it. The lesson is that even the smallest useful program tends to reach for all five, which is why the list is short enough to be worth memorising.
Explain it to yourself
Answer in your own words, out loud or on paper. This is a check on understanding, not on memory.
Discussion prompt
Somebody says: there must be more than five kinds of instruction, because Python has hundreds of built-in functions. Reply to them in two or three sentences.
Hint: The distinction you need is between a KIND of instruction and a NAME for a combination of them.
Answer:
Hundreds of built-in functions are hundreds of NAMES, not hundreds of kinds. Each one was written, by somebody, out of the same five categories.
A useful analogy: English has hundreds of thousands of words but only a handful of parts of speech. Learning that a word is a verb tells you a great deal about how it behaves in a sentence, without telling you what it means.
The five categories are the parts of speech of programming. The names are vocabulary, and vocabulary is learned as you need it.
Section
Section 3
Concept
You can think of programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions.
decomposition — Breaking a task into subtasks, and those into smaller subtasks, until each one is a single basic instruction.
Notice the stopping condition. You are not breaking things down until they feel simple, or until you get bored. You are breaking them down until each piece is one of the five. That is a test you can actually apply.
Figure (svg): A four-rung ladder showing a task being broken down in stages, from greet the user by name at the top to three single instructions at the bottom
Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 2-2
Picture it
Each level down is more pieces, and each piece is simpler than its parent.
Figure (svg): A flow chart showing a task box splitting into two subtask boxes and those splitting again into single instructions, with a test asking whether each piece is one of the five categories
The test in the diamond is the reason the five-item list is worth knowing by heart. Without it you have no way to tell whether you have finished decomposing.
Worked example
Do the decomposition on paper before you look. Aim to stop at the five categories.
name = input('What is your name? ')
count = len(name)
print(count)| Line | The subtask it performs | Category |
|---|---|---|
| 1 | get text from the keyboard | input |
| 2 | count the letters in it | math |
| 3 | show the count | output |
Say the task out loud and listen for the verbs.
Why: Tell, count, and an implied ask. Three verbs is a strong hint at three subtasks.
Check each subtask against the five categories.
Why: Asking is input. Counting is math. Telling is output. All three pass the test, so the decomposition stops here.
Write one line per subtask, in the order they must happen.
Why: Counting cannot precede asking, and telling cannot precede counting. The order is forced by what each step needs from the one before.
Figure (svg): The state of the program after each line of Worked example decompose tell me how many letters are in my name , drawn as a ladder with one rung per traced line
Three subtasks, three lines, and each one is a single basic instruction. The decomposition stopped because every piece passed the five-category test, not because three felt like enough.
Verify: Try to split any of the three lines further and see whether the pieces are still meaningful.
Why: Splitting count the letters into smaller steps would mean describing how counting works — which is real work, but work Python has already done and packaged as len. Being unable to usefully split further is exactly the signal that the decomposition is complete.
Ranking
These five lines are one decomposition, shuffled. Put them back.
Put in order
Why: The task comes first and gets progressively more specific: the English task, a split into two halves, a split into three concrete steps, the category labels that prove the split is finished, and finally one of the actual instructions. The last item is deliberately a single line rather than a summary — the end of a decomposition is code, not a better description of code.
Worked example
Here is the same task, decomposed by somebody who stopped when the pieces felt simple.
# ask the user for their name
# work out the length
# tell them the answer| Line | What Python does with it | Effect |
|---|---|---|
| 1 | a comment, not an instruction | nothing runs |
| 2 | a comment, not an instruction | nothing runs |
| 3 | a comment, not an instruction | nothing runs |
Apply the five-category test to each line.
Why: Each one describes a subtask rather than naming an instruction. None of them is input, output, math, a condition or a loop — they are English about those things.
Notice that Python accepts this file without complaint.
Why: Every line begins with a hash, which makes it a comment. The program is legal, runs successfully, and does nothing at all.
Recognise the failure mode.
Why: This is not a broken program. It is a plan that was mistaken for a program, and it is the most common thing a beginner produces when the decomposition stops early.
Figure (svg): Two columns comparing three comment lines that do nothing against three real instructions that do the same job
The program runs, produces no output, and reports no error. The decomposition stopped one level too high: three English descriptions, none of which is one of the five basic instructions.
Verify: Ask what the program would print if you ran it, and then run it.
Why: Nothing prints. A plan that produces no output when you expected output is the clearest evidence that the pieces are still descriptions — and this is worth experiencing once deliberately, because it will happen to you accidentally later.
Trap
Get the user's details and validate them feels like one simple step to a person who has done it a hundred times.
Judge simplicity by familiarity
Why: Familiar tasks feel atomic. That feeling has nothing to do with whether Python has an instruction for them.
Written as one line, it is a description. Python has no instruction called validate, and no opinion about what details means.
Judge simplicity by the five-category test, which does not care what you find familiar.
Ask of each piece: is this input, output, math, a condition, or repetition?
Why: If the answer is sort of, it involves several of those, the piece is not finished.
Split until every answer is a single unhesitating yes
Why: Get the details becomes several inputs. Validate them becomes several conditions.
The test is deliberately mechanical, because your intuition about difficulty is calibrated for people and Python is not a person.
Step zero
This is the situation you will be in for most of chapters 4, 9 and 13.
Discussion prompt
You are asked to write a program that finds the longest word in a book. You have no idea how to start. What is the FIRST thing you write down — and it is not code.
Hint: The answer is a move from this section, not a piece of Python.
Answer:
Write down the task in English, then split it once. Find the longest word in a book splits into read the book's words and find the longest of a pile of words.
Neither half is code yet, and neither has to be. You have turned one problem you cannot picture into two problems that are visibly smaller, and you can now attack whichever one you understand better.
Do it again on each half. You will hit the five categories within two or three rounds, and at that point the code writes itself. This is the whole method, and it does not stop being the method when the problems get hard.
Elimination
Three of these are single basic instructions. One is still a description.
Eliminate the wrong options
Which of these has NOT been decomposed far enough to write as one instruction?
Survives elimination: C
Why: C fails the five-category test on both of its key words. Handle is not one of the five — it is a stand-in for whatever combination of conditions and outputs turns out to be needed. Appropriately is worse: it hides a condition that has not been stated, and until it is stated nobody can write the code. The other three each name one category, name the data they act on, and leave nothing for the reader to invent.
Counterexample
The section has been arguing that descriptions are not programs. Push back on it.
Discussion prompt
Give an example of an English sentence that is BOTH a reasonable description of a task AND, essentially unchanged, a working line of Python. What makes it possible?
Hint: Think about how the print function reads out loud.
Answer:
Print the words Hello, World! is a description. print('Hello, World!') is a program. They differ by punctuation, not by content.
This is possible exactly when the task is already a single basic instruction and Python's name for that instruction happens to be the English verb. The library designers chose those names on purpose.
It is worth noticing because it explains why the very first program in every language is a print statement: it is the one task where description and instruction coincide, so nothing about decomposition has to be taught before it works.
Section
Section 4
Concept
The Python interpreter is a program that reads and executes Python code. Depending on your environment, you might start it by clicking an icon or by typing python on a command line.
interpreter — A program that reads another program and executes it.
Python 3.4.0 (default, Jun 19 2015, 14:20:21)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> | Line | What the interpreter is telling you | What to do about it |
|---|---|---|
| 1 | the interpreter names its own version | check this begins with a 3 |
| 2 | it names the compiler and operating system | will differ on your machine |
| 3 | it offers four words you can type for help | safe to ignore for now |
| 4 | it prints the prompt and waits | your turn |
The first three lines are about the interpreter, not about you, and they will look different on your machine. The last line is the one that matters: it is a prompt, and it means the interpreter is ready for you to enter code.
Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 2-2
Picture it
The prompt is not decoration. It marks one full turn of a cycle the interpreter never leaves.
Figure (svg): A flow chart showing the interpreter printing a prompt, reading a line, evaluating it, printing the result, and looping back to the prompt
Every interactive example in this book is one turn of this loop: you supply the line, the interpreter supplies everything else.
Worked example
Two lines. Decide which one you typed and which one the interpreter produced.
>>> 1 + 1
2| Line | Who does what | State after |
|---|---|---|
| 1 | you type 1 + 1 after the prompt and press Enter | the interpreter now has a line to evaluate |
| 1 | the interpreter evaluates it | the value 2, held but not yet shown |
| 2 | the interpreter displays the result | 2 appears, with no prompt in front of it |
Find the prompt.
Why: The three angle brackets are printed BY the interpreter, before you type. Everything after them on that line is yours.
Read the second line's lack of a prompt as information.
Why: No prompt means the interpreter wrote it. That is the only reliable way to tell input from output in a transcript, and it is why the book prints the prompt at all.
Match the result to the line that produced it.
Why: The value 2 is the result of evaluating the expression on the line above it.
Figure (svg): A two-row diagram showing the typed expression on the left and the displayed value it evaluates to on the right
You typed 1 + 1 — everything after the prompt on the first line. The interpreter printed 2, on a line with no prompt. The transcript records one full turn of the read-evaluate-print loop.
Verify: Count the prompts and the results in the transcript.
Why: One prompt and one result. If a transcript ever shows two results after one prompt you have either mis-transcribed it or the line did something more interesting than evaluate to a value — and both are worth stopping to investigate.
Prediction
A very common first-day mistake, and the error message is not obvious.
Predict first
You copy an example from the book INCLUDING the three angle brackets, and press Enter. What happens?
Correct: A syntax error, because the angle brackets are not valid Python at the start of a line.
Why: The three angle brackets are output from the interpreter, not part of any example. Typed as input they are read as comparison operators with nothing on their left, which is not a legal expression, so Python reports a syntax error. It is worth causing this error on purpose once: it teaches you to read the prompt as belonging to the machine, and it makes the error message familiar in a situation where you already know the cause.
Worked example
There are two versions of Python in the world and this book is written for one of them.
Python 3.4.0 (default, Jun 19 2015, 14:20:21)
Python 2.7.6 (default, Nov 23 2017, 15:49:48)| Banner line | What to look at | What it means |
|---|---|---|
| 1 | the version begins with 3 | this is Python 3 — the book's version |
| 2 | the version begins with 2 | this is Python 2 — a few things will differ |
Ignore everything except the first number after the word Python.
Why: The rest of the banner is the exact release, the build date and the compiler — none of which changes how your code behaves.
Read the first digit.
Why: A 3 means you are running Python 3. A 2 means Python 2, which is very similar but differs in a few places you would meet as a beginner.
Decide what to do if it says 2.
Why: The languages are close enough that learning one makes switching easy, but this book is written for 3, so it is worth finding a 3 before going further.
Figure (svg): The state of the program after each line of Worked example checking which Python you are running, drawn as a ladder with one rung per traced line
Look at the first digit of the version number and nothing else. The first banner is Python 3, the second is Python 2, and this book assumes the first.
Verify: Check the claim against the very next thing the book teaches.
Why: The first program is print('Hello, World!') with parentheses. In Python 2 the same idea is written without them, which means the version check is not academic — it changes whether the next page's program runs.
Error analysis
A student copied an interpreter session into their notes. Two things about it will mislead them later. Mark them.
Annotate
This is why the book prints the prompt in its examples and why you should never type it. It is punctuation belonging to the interpreter.
Discrimination
The whole skill is telling input from output, and the prompt is the only clue you need.
Sort into buckets
Sort each line of this transcript by who produced it.
Analogy
Map each part of the session onto something you already do without thinking.
Match the pairs
Why: The analogy is worth taking seriously because it predicts things correctly. A conversation has turns, so you wait for the prompt before typing. A reply is about the thing just said, so a result belongs to the line above it. And an introduction happens once, at the start, which is why the banner never reappears. Where the analogy breaks down is memory: the interpreter remembers everything you have told it in this session, and forgets all of it when the session ends.
Edge cases
The read-evaluate-print loop has to do something. Predict what, then reason about why.
Discussion prompt
You press Enter at the prompt without typing anything. Describe what the interpreter does, and explain which of the four steps of the loop had nothing to do.
Hint: It certainly does not crash. Walk the four steps and ask what each one has to work with.
Answer:
It prints a fresh prompt and waits again. Nothing else happens and nothing is displayed.
Reading succeeded — an empty line is a line. Evaluating an empty line produces no value, so the print step has nothing to display and displays nothing. Then the loop comes round to the prompt again.
This is the smallest possible demonstration that the loop is genuinely a loop rather than a one-shot: it came back to the prompt without you having given it anything to do. Programs that quietly do nothing are a theme of this course, and the empty line is the gentlest example of one.
Section
Section 5
Concept
Traditionally, the first program you write in a new language is called Hello, World, because all it does is display the words Hello, World. In Python it looks like this, and it is a complete program.
print('Hello, World!')| Part | What it is | Shows on screen? |
|---|---|---|
| the name of a function Python already has | output | |
| ( ) | the parentheses that make it a CALL rather than a mention | required |
| ' ' | the quotation marks marking where the text starts and stops | not displayed |
| Hello, World! | the text itself | displayed |
This is an example of a print statement, although it does not actually print anything on paper — it displays a result on the screen. The quotation marks mark the beginning and end of the text to be displayed; they do not appear in the result. The parentheses indicate that print is a function, which chapter 3 makes precise.
Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 3-3
Picture it
Four of the characters you type are instructions to Python. The rest are the message.
Figure (svg): The characters of the Hello World program drawn as a row of boxes with the quotation marks and parentheses highlighted as structure rather than content
Getting this distinction wrong is the source of the two most common first-week errors, and both of them appear in the next lesson's debugging section.
Worked example
Type it at the prompt exactly as written, then account for every character of the output.
print('Hello, World!')| Line | What Python does | Result |
|---|---|---|
| 1 | Python reads the whole line | an instruction to call print |
| 1 | it evaluates what is inside the parentheses | the text Hello, World! |
| 1 | it calls print with that text | Hello, World! appears on the screen |
Account for the parentheses in the output.
Why: They do not appear. Their job was to say that print is being called, and that job is finished before anything is displayed.
Account for the quotation marks in the output.
Why: They do not appear either. Their job was to mark where the text began and ended, so Python could tell the message from the code around it.
Account for the exclamation mark.
Why: It DOES appear, because it is inside the quotation marks. Punctuation inside the quotes is part of the message; punctuation outside is part of the program.
Figure (svg): The state of the program after each line of Worked example running Hello, World and reading the result, drawn as a ladder with one rung per traced line
The screen shows exactly Hello, World! — thirteen characters. The parentheses and quotation marks were structure and vanished; everything between the quotes was content and survived.
Verify: Count the characters between the quotation marks and compare with the characters on the screen.
Why: Thirteen in the source, thirteen on the screen, in the same order. This is a check you can run on any print statement, and when the counts disagree it is nearly always a quotation mark in the wrong place.
Faded example
Two blanks. Each one is a piece of structure, not a piece of the message.
Fill in the blanks
print('Good morning')
Why: The parentheses are what make this a call to the print function rather than a mention of the name print. Without them, Python 3 reports a syntax error — it can see you naming a function and then, unaccountably, a piece of text. The quotation marks were supplied for you because they mark the message, and the message was not what this exercise was about.
Worked example
The book mentions this in passing, and it is the difference you are most likely to actually meet.
print 'Hello, World!'| Which Python | How print is treated | What happens |
|---|---|---|
| Python 3 | print is a function, so a call needs parentheses | SyntaxError |
| Python 2 | print is a statement, so no parentheses are used | Hello, World! |
| either | the quotation marks behave identically | the text is the text |
Notice what changed and what did not.
Why: The parentheses are gone. The quotation marks, the text and the word print are all unchanged.
Connect the change to the reason for it.
Why: In Python 2 the print statement is slightly different: it is not a function, so it does not use parentheses. Everything the parentheses were for stops applying.
Decide what to do when you meet this in the wild.
Why: Code with parentheses-free print is Python 2 code. Adding the parentheses is usually all it takes to run the line under Python 3.
Figure (svg): Two columns showing the Python 3 print call with parentheses beside the Python 2 print statement without them
Without parentheses the line is a Python 2 print statement. Under Python 3 it is a syntax error, because print is a function there and calling a function requires parentheses.
Verify: Check the diagnosis against the version banner from the previous section.
Why: The two checks agree: a banner beginning with 2 predicts that parentheses-free print will work, and a banner beginning with 3 predicts a syntax error. Two independent signals pointing at the same conclusion is what makes this a diagnosis rather than a guess.
Trap
Asked to display the words Hello, World!, a beginner writes the whole line inside the quotes:
print('print(Hello, World!)')
Treat the quotes as decoration on the outside of the instruction
Why: Quotes look like the punctuation you would use to quote something in English, where they go around the whole quoted sentence.
Python obediently displays the characters print(Hello, World!) on the screen, which is a correct execution of a program that was not the one intended.
The quotes go around the MESSAGE, and nothing else:
Decide first what should appear on the screen
Why: The words Hello, World! and nothing more.
Put quotation marks immediately around exactly that
Why: Anything inside them is content. Anything outside them is program.
print('Hello, World!') displays Hello, World! — the quotes marked the message, the parentheses marked the call, and neither appeared in the result.
The diagnostic question, whenever output looks wrong: which characters did I put inside the quotes? Whatever they were, those are the characters you asked for.
Prediction
Read it as Python does: find the quotes first, then decide what is inside them.
print('It costs (5) dollars')| Line | What Python looks for | Consequence |
|---|---|---|
| 1 | find the outer parentheses | they mark the call |
| 1 | find the quotation marks inside them | they mark the message |
| 1 | display everything between the quotes | the inner parentheses are inside |
Predict first
What appears on the screen?
Correct: It costs (5) dollars — the inner parentheses are inside the quotation marks, so they are part of the message.
Why: Python finds the quotation marks first and treats everything between them as text, with no further interpretation. The inner parentheses are therefore ordinary characters, exactly like the letters around them, and they are displayed. The outer parentheses are outside the quotes and so remain structure, marking the call to print. This is the same rule as the exclamation mark in Hello, World!, applied to a character that happens to look like syntax.
Error analysis
One of these works. Mark what is wrong with the other two, and say what each would do.
Annotate
Both broken lines fail before anything is displayed. A syntax error means Python never started running the program.
Constraint
The rule you just learned creates a problem. Work out what it is before reading on.
Discussion prompt
You want the screen to show: It's fine. But the quotation marks around your message are single quotes, and there is now a single quote inside the message too. What goes wrong, and what would you try?
Hint: Python finds the quotes first, and it stops at the first closing one it meets.
Answer:
Python reads print('It's fine') and sees the message as It, ending at the apostrophe. The rest of the line is then leftover text it cannot make sense of, and you get a syntax error.
The simplest fix is to mark the message with double quotes instead, which the apostrophe cannot be confused with. Python accepts either kind, and this is exactly why it accepts both.
There is a second fix, using a backslash before the apostrophe to say this one is content, not a marker. Both are worth knowing, and the second becomes important in chapter 8 when strings get more serious.
Comparison
Fill the blanks from memory. If you can rebuild this table, you have the taxonomy.
Comparison matrix
| Category | What it does | Where you meet it in this book |
|---|---|---|
| input | gets data from the keyboard, a file or the network | the input function; files in chapter 14 |
| output | displays data, or saves and sends it | the print function, starting in this lesson |
| math | performs basic operations like addition and multiplication | the operators, in the next lesson |
| conditional execution | checks a condition and runs the appropriate code | the if statement, chapter 5 |
| repetition | performs an action repeatedly, usually with variation | while and for, chapters 7 and 8 |
The middle column is the definition and the right column is the itinerary. Between them they are a map of everything ahead.
Pattern
This is the loop you will run for every exercise in this book, and it does not change as the problems get harder.
Step 6 is not optional and it is not a formality. Predicting the output before you run it is the only way to find out whether you understood the program, as opposed to whether the program happened to work.
Python documentation — Whetting Your Appetite Whetting Your Appetite
Check
One sentence, two halves. Which option gets both right?
Check your understanding
Which of these is the book's definition of a program?
Answer: B
Why: The definition has two halves and B is the only option with both. SEQUENCE, because the instructions happen in an order and reordering them changes the program. And HOW to perform a computation, because a program is a method rather than a wish. Getting either half wrong leads to a specific, predictable mistake, which is why the wording is worth being fussy about.
Check
Only one thing distinguishes what you typed from what the interpreter said.
>>> 6 * 7
42| Line | What is there | Who produced it |
|---|---|---|
| 1 | a prompt, then an expression | typed by the human |
| 1 | the interpreter evaluates it | the value 42 |
| 2 | no prompt, just a value | printed by the interpreter |
Check your understanding
In this transcript, how do you know that 42 was produced by the interpreter rather than typed?
Answer: C
Why: The prompt marks authorship, and that is its whole job in a transcript. A line beginning with the three angle brackets was typed by the person; a line without them was printed by the interpreter. This is the only signal that works in general, which is why it is the one to rely on.
Check
Find the quotation marks first, exactly as Python does.
print('Total: (12 items)')| Line | What Python identifies | Role |
|---|---|---|
| 1 | the outer parentheses mark the call | structure |
| 1 | the quotation marks mark the message | structure |
| 1 | everything between the quotes is displayed | content |
Check your understanding
What appears on the screen?
Answer: B
Why: Everything between the quotation marks is content and is displayed unchanged, including the inner parentheses. The quotation marks themselves are structure and do not appear, and neither do the outer parentheses, whose job was to mark the call to print. Content survives, structure vanishes.
Real world
The five categories are not a Python idea, and neither is decomposition.
Discussion prompt
Pick something you do that is not programming — a recipe, a set of driving directions, an assembly instruction sheet. Identify one step that is input, one that is a condition, and one that is repetition. Then find a step that is written like a description rather than an instruction, and say what would go wrong if you followed it literally.
Hint: Recipes are full of season to taste, which is a description wearing the clothes of an instruction.
Answer:
Recipes are the clearest case. Preheat the oven to 200 is an instruction. Stir until thickened is a condition plus repetition. Season to taste is a description, and following it literally is impossible — it delegates a decision back to you.
Driving directions have the same structure: turn left at the lights is a condition on arriving at the lights, continue for two miles is repetition with a stopping test.
The reason this transfers is that decomposition is not about computers. It is about making a method precise enough that somebody who knows nothing about your intentions can follow it — and a computer is simply the least forgiving reader you will ever have.
Commit first
Answer, then say how sure you are. Being wrong while certain is the most useful thing that can happen in a first lesson.
Predict first
A file contains three lines, each beginning with a hash. You run it. What happens?
Correct: It runs successfully and produces no output — every line is a comment, so the program is legal and does nothing.
Why: This is the failure mode from the decomposition section, met again as a prediction. Nothing is wrong with the file: comments are legal Python, a program made entirely of them is a legal program, and running it succeeds. The absence of output is the only symptom, which is precisely what makes it confusing the first time. If you were confident about a syntax error, that is worth noticing — the intuition that nothing happened means something broke is wrong often enough to be worth unlearning early.
Explain it
Explaining is the fastest way to find the parts you only think you understand.
Discussion prompt
A friend has installed Python, sees the three angle brackets, and asks what am I supposed to do with this? Explain, in under a minute, what the prompt is, what will happen when they type something, and what the first thing worth typing is.
Hint: Their real question is whose turn is it, even though they did not ask it that way.
Answer:
A good answer says three things. The prompt means the interpreter is waiting for you. Whatever you type gets read, worked out and displayed. And 1 + 1 is the smallest thing that proves all of that at once.
A good answer also does NOT start with functions, syntax or the five categories. Your friend has one question — whose turn is it — and answering a different question is the most common way an explanation fails.
If they type print('Hello, World!') next, they will have written a program, which is a reasonable thing to have done within a minute of meeting the language.
Exit ticket
One honest answer. It decides what the next lesson opens with.
Predict first
Which of these is still least solid for you?
Correct: Whichever you picked is the right answer — this one is for you, not for a mark.
Why: These four are not equally hard. The definition is a sentence you can memorise today. The categories take a week of noticing. Decomposition takes the whole book, and it is the one that separates people who can write programs from people who can read them. Reading a transcript is the one that stops being a problem the moment you have made the mistake once. Knowing which of them is your weak spot is worth more than a score.
Connect it up
One page, no code, from memory. Do it before the next lesson rather than after.
Draw it
Draw a single diagram that connects: the definition of a program, the five kinds of instruction, decomposition, the interpreter, and Hello, World. Put an arrow from each thing to the thing it makes possible, and write one sentence on each arrow saying why. There is more than one defensible arrangement — the sentences on the arrows are the part that matters.
Recap
Five pages of a book, and the vocabulary for everything that follows.
| If you remember one thing | It is this |
|---|---|
| From the definition | Sequence. The order is part of the meaning, not part of the layout. |
| From the taxonomy | Five categories, and every unfamiliar name is a combination of them. |
| From decomposition | Stop when each piece is one of the five — not when it feels simple. |
| From the interpreter | The prompt belongs to the machine. Never type it. |
| From Hello, World | What is inside the quotes is the message. Everything else is the program. |
The next lesson turns the prompt into a calculator, meets the first three types of value, and produces your first real error message on purpose.
Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 1-3 — everything on these slides traces back here
Want this taught 1-on-1? Alexander tutors Python — $55/session, free consultation.