1a What a Program Is, and How to Run One

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

What this lesson covers

The lesson, slide by slide

1. Lesson 1a What a Program Is, and How to Run One

Title

Python · Chapter 1 — The way of the program

§1.1-1.3, pp. 1-3

2. By the end of this lesson you can

Objectives

Five things, each one you can check yourself at an interpreter prompt.

Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 1-3 — the pages these objectives are drawn from

3. Before we start: you already know what a program does

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.

4. The one idea behind everything in this course

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

Everything else in this book is a refinement of this picture.

Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 1-1 — the definition, in the book's own words

5. A program is a sequence, and the order is part of the meaning

Section

Section 1

6. Why *sequence* is the load-bearing word

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!')
LineWhat runsWhat is on the screen after it
1print('Ready?')Ready?
2print('Set.')Ready? Set.
3print('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

7. Picture it: a program is a stack of instructions with a finger moving down it

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

One rung per line. The arrow is the only control structure you know so far.

Every new construct in this book is a way of changing which rung the arrow goes to next. That is genuinely all they are.

8. Worked example: predict the output of a four-line program

Worked example

Write down what you think appears on the screen, in order, before you advance.

print('first')
print('second')
print('third')
print('first')
LineWhat runsScreen so far (comma-separated)
1print('first')first
2print('second')first, second
3print('third')first, second, third
4print('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 whole run at once: each drop is one line of the program.

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.

9. Predict: does swapping two lines always change the output?

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?

  • Yes — order is part of the meaning, so any swap changes the result
  • No — it depends on what the two lines are
  • Only if the two lines print different things
  • Only in Python; other languages are order-independent

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.

10. Worked example: the same three lines, reordered

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?')
LineWhat runsWhat is on the screen after it
1print('Go!')Go!
2print('Set.')Go! Set.
3print('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

Same three instructions. Two programs.

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.

11. Trap: writing down the goal instead of the steps

Trap

The 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.

The fix

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.

12. Sort: is this a program, or a description of one?

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.

A program: instructions Python can carry out
print('Hello'); print('Hello'); print('Hello'); print('Welcome')
A description: what you want, not how to get it
say hello to the user; show a friendly greeting twice; make the screen welcoming
prog
Each of these names an instruction Python already has, with everything it needs supplied. Python can run it without asking you a single question.
desc
Each of these leaves the actual instruction unstated. They are perfectly good English and completely useless to an interpreter, because none of them says which instruction to carry out.

13. Think it through: why does a script need a first line?

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.

14. Two truths and a lie: what a program is

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.

  • A. A program's instructions are carried out in a definite order
  • B. A program specifies HOW to perform a computation, not merely what result is wanted
  • C. Two programs made of the same instructions always produce the same result

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.

15. There are only about five kinds of instruction

Section

Section 2

16. The whole taxonomy, in one list

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

17. Picture it: five boxes that every program is built from

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

Chapters 1 to 7 of this book introduce these five, one or two at a time.

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.

18. Worked example: labelling every line of a small program

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.')
LineWhat it doesWhich of the five
1ask the keyboard for textinput
2count the lettersmath
3compare the count with 8conditional execution
4display one messageoutput
6display the other messageoutput

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.

19. Definition probe: sort these actions into the five categories

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?

input
reading the text you typed into a search box; loading a saved game from a file
output
showing a list of results on the screen
math
adding up the items in a shopping basket
conditional execution
showing a warning only when the password is too short
repetition
sending the same reminder to every name on a list
in
Data arrives from outside the program — from the keyboard in one case and from a file in the other. The device differs; the category does not.
out
Data leaves the program and becomes visible. The screen is the usual destination, but a file or the network would be the same category.
math
A basic mathematical operation on values the program is holding. Addition is the clearest case of it.
cond
A condition is checked and the appropriate code runs. The giveaway word is only when.
rep
One action performed repeatedly, with variation — a different name each time round. The giveaway word is every.

20. Worked example: which category is missing, and what would add 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)
LineWhat it doesWhich of the five
1ask the keyboard for textinput
2start a loop over the lettersrepetition
3display one letteroutput (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

The whole run at once: each drop is one line of the program.

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.

21. Trap: thinking a longer program needs more than five kinds of instruction

Trap

The 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.

The fix

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.

22. Match each category to the Python you will meet

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

  • in. input
  • out. output
  • math. math
  • cond. conditional execution
  • rep. repetition
  • r1. the input function, and reading files in chapter 14
  • r2. the print function, from this lesson onward
  • r3. the operators plus, minus and star, in the next lesson
  • r4. the if statement, in chapter 5
  • r5. the while and for statements, in chapters 7 and 8

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.

23. Estimate: how many of the five does a calculator app use?

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?

  • Two
  • Three
  • Four
  • All five

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.

24. Explain it yourself: why is the list five items and not fifty?

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.

25. Programming is breaking a task into instructions that small

Section

Section 3

26. The move that makes the five categories useful

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

Stop when every piece is one of the five. Not before, not after.

Think Python, 2nd edition — Allen B. Downey §1.1-1.3, pp. 2-2

27. Picture it: decomposition is a tree you stop growing at a rule

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.

28. Worked example: decompose *tell me how many letters are in my name*

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)
LineThe subtask it performsCategory
1get text from the keyboardinput
2count the letters in itmath
3show the countoutput

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

The whole run at once: each drop is one line of the program.

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.

29. Rank: put a decomposition in order from task to instructions

Ranking

These five lines are one decomposition, shuffled. Put them back.

Put in order

  1. work out the total cost of a shopping basket and show it
  2. add up the prices, then display the result
  3. get the prices, add them, print the sum
  4. input | math | output
  5. print the total

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.

30. Worked example: a decomposition that stops too early

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
LineWhat Python does with itEffect
1a comment, not an instructionnothing runs
2a comment, not an instructionnothing runs
3a comment, not an instructionnothing 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

Both files run without error. Only one of them is a program that does the task.

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.

31. Trap: decomposing until it feels simple rather than until it passes the test

Trap

The 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.

The fix

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.

32. Step zero: what would you do first with a task you cannot picture?

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.

33. Eliminate: which piece is not yet finished being decomposed?

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?

  • A. display the number 7 on the screen
  • B. add 3 and 4 together
  • C. handle the user's request appropriately
  • D. read a line of text from the keyboard

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.

34. Find the counterexample: when is a one-line description already a program?

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.

35. The interpreter: the program that runs your program

Section

Section 4

36. What is actually reading what you type

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.
>>> 
LineWhat the interpreter is telling youWhat to do about it
1the interpreter names its own versioncheck this begins with a 3
2it names the compiler and operating systemwill differ on your machine
3it offers four words you can type for helpsafe to ignore for now
4it prints the prompt and waitsyour 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

37. Picture it: the read-evaluate-print loop

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.

38. Worked example: reading an interpreter session

Worked example

Two lines. Decide which one you typed and which one the interpreter produced.

>>> 1 + 1
2
LineWho does whatState after
1you type 1 + 1 after the prompt and press Enterthe interpreter now has a line to evaluate
1the interpreter evaluates itthe value 2, held but not yet shown
2the interpreter displays the result2 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

The prompt is the interpreter's way of saying whose turn it is.

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.

39. Predict: what happens if you type the prompt yourself?

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?

  • It works — Python ignores the prompt characters
  • A syntax error, because the angle brackets are not valid Python there
  • Nothing at all — the line is treated as a comment
  • Python prints the prompt back at you

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.

40. Worked example: checking which Python you are running

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 lineWhat to look atWhat it means
1the version begins with 3this is Python 3 — the book's version
2the version begins with 2this 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

The whole run at once: each drop is one line of the program.

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.

41. Error analysis: a transcript copied out wrongly

Error analysis

A student copied an interpreter session into their notes. Two things about it will mislead them later. Mark them.

Annotate

  • Line 1 is correct: a prompt, then an expression the student typed.
  • Line 2 is the mistake. The value 2 was printed BY the interpreter, so it never had a prompt in front of it. Writing one there records it as something the student typed.
  • That matters because typing 2 at the prompt is a legal thing to do, and it would also display 2 — so the corrupted transcript is not obviously wrong, it just says something different from what happened.
  • Lines 3 and 4 are recorded correctly: a prompt on the line that was typed, no prompt on the line the interpreter produced.
  • The rule to take away: in a transcript, the prompt is the marker for authorship. Add one where it does not belong and you have changed who did what.

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.

42. Discriminate: which lines did the human write?

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.

the human typed it
>>> 40 + 2; >>> print('done')
the interpreter printed it
42; done; Python 3.4.0 (default, Jun 19 2015)
human
Both of these follow a prompt on the same line. Everything after the three angle brackets is what the person at the keyboard supplied.
machine
None of these has a prompt in front of it. Two are results of evaluating the line above, and the third is the banner the interpreter prints before the session even starts.

43. Analogical pivot: the interpreter as a conversation

Analogy

Map each part of the session onto something you already do without thinking.

Match the pairs

  • p. the prompt
  • t. the line you type
  • r. the result it displays
  • b. the banner at the start
  • r1. the other person pausing to let you speak
  • r2. what you say
  • r3. their reply
  • r4. them introducing themselves before you begin

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.

44. Push the boundary: what does the interpreter do with an empty line?

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.

45. Hello, World: the first program, character by character

Section

Section 5

46. The traditional first program, and why it is traditional

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!')
PartWhat it isShows on screen?
printthe name of a function Python already hasoutput
( )the parentheses that make it a CALL rather than a mentionrequired
' 'the quotation marks marking where the text starts and stopsnot displayed
Hello, World!the text itselfdisplayed

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

47. Picture it: which characters survive to the screen

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

The highlighted characters are structure. Everything between the quotes is 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.

48. Worked example: running Hello, World and reading the result

Worked example

Type it at the prompt exactly as written, then account for every character of the output.

print('Hello, World!')
LineWhat Python doesResult
1Python reads the whole linean instruction to call print
1it evaluates what is inside the parenthesesthe text Hello, World!
1it calls print with that textHello, 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 whole run at once: each drop is one line of the program.

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.

49. Complete the program: fill in what is missing

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.

50. Worked example: the Python 2 version, and why it differs

Worked example

The book mentions this in passing, and it is the difference you are most likely to actually meet.

print 'Hello, World!'
Which PythonHow print is treatedWhat happens
Python 3print is a function, so a call needs parenthesesSyntaxError
Python 2print is a statement, so no parentheses are usedHello, World!
eitherthe quotation marks behave identicallythe 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

Same output, two versions of the language. This book uses the right-hand column.

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.

51. Trap: putting the quotation marks around the wrong thing

Trap

The 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 fix

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.

52. Predict: what does this display?

Prediction

Read it as Python does: find the quotes first, then decide what is inside them.

print('It costs (5) dollars')
LineWhat Python looks forConsequence
1find the outer parenthesesthey mark the call
1find the quotation marks inside themthey mark the message
1display everything between the quotesthe inner parentheses are inside

Predict first

What appears on the screen?

  • It costs 5 dollars
  • It costs (5) dollars
  • A syntax error, because of the nested parentheses
  • It costs dollars

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.

53. Error analysis: three attempts at Hello, World

Error analysis

One of these works. Mark what is wrong with the other two, and say what each would do.

Annotate

  • Line 1 has no parentheses. Under Python 3 that is a syntax error, because print is a function and a call needs them. Under Python 2 it would have worked, which is why you will see this line in older code.
  • Line 2 opens a quotation mark but never closes it. Python reads to the end of the line still looking for the closing quote and reports an unterminated string.
  • The closing parenthesis on line 2 does not help, because it is inside the string as far as Python is concerned — it came after the opening quote and before any closing quote.
  • Line 3 is correct: print, open parenthesis, open quote, the message, close quote, close parenthesis. Every opener has its matching closer, in the right order.
  • The pattern behind both errors is the same: an opener without its closer. Checking that every parenthesis and every quotation mark is paired will catch the great majority of first-week syntax errors.

Both broken lines fail before anything is displayed. A syntax error means Python never started running the program.

54. Constraint challenge: display a quotation mark

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.

55. Compare: the five kinds of instruction side by side

Comparison

Fill the blanks from memory. If you can rebuild this table, you have the taxonomy.

Comparison matrix

CategoryWhat it doesWhere you meet it in this book
inputgets data from the keyboard, a file or the networkthe input function; files in chapter 14
outputdisplays data, or saves and sends itthe print function, starting in this lesson
mathperforms basic operations like addition and multiplicationthe operators, in the next lesson
conditional executionchecks a condition and runs the appropriate codethe if statement, chapter 5
repetitionperforms an action repeatedly, usually with variationwhile 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.

56. The procedure: from a task in English to a running program

Pattern

This is the loop you will run for every exercise in this book, and it does not change as the problems get harder.

  1. Write the task down in English, as one sentence.
  2. Split it into subtasks, each one smaller than the whole.
  3. Test every subtask against the five categories: input, output, math, conditional execution, repetition.
  4. Any subtask that is not one of the five, split again. Repeat until they all pass.
  5. Write one instruction per subtask, in an order where nothing needs a value that has not been produced yet.
  6. Run it at the prompt and compare what appeared with what you predicted.

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

57. Check yourself 1 of 3: the definition

Check

One sentence, two halves. Which option gets both right?

Check your understanding

Which of these is the book's definition of a program?

  • A. A set of instructions a computer can carry out
  • B. A sequence of instructions that specifies how to perform a computation (correct)
  • C. A description of a result you want a computer to produce
  • D. A list of the five basic operations, applied to some data

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.

Why A tempts people
Says set rather than sequence, and a set has no order. This is the half that the reordered greeting program disproves: same set of instructions, different output.
Why C tempts people
Describes the result rather than the method, which is the trap from the first section. Greet the user three times is a description; three print statements are a program.
Why D tempts people
Confuses the definition with the taxonomy. The five categories are what the instructions turn out to be, not what the word program means — and a program need not use all five.

58. Check yourself 2 of 3: reading a transcript

Check

Only one thing distinguishes what you typed from what the interpreter said.

>>> 6 * 7
42
LineWhat is thereWho produced it
1a prompt, then an expressiontyped by the human
1the interpreter evaluates itthe value 42
2no prompt, just a valueprinted by the interpreter

Check your understanding

In this transcript, how do you know that 42 was produced by the interpreter rather than typed?

  • A. Because it is a number, and numbers are always results
  • B. Because it is on the second line, and results always come second
  • C. Because it has no prompt in front of it (correct)
  • D. Because 6 times 7 is 42, so it must be the answer

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.

Why A tempts people
Numbers can perfectly well be typed — entering 42 at the prompt is legal and displays 42. Being a number says nothing about who wrote it.
Why B tempts people
Position is not reliable. A session has many turns, and a typed line can appear on the second, tenth or hundredth line of a transcript.
Why D tempts people
This reasons from the arithmetic rather than from the transcript. It happens to reach the right conclusion here, but it would fail on any line whose result you could not compute in your head — which is most of them.

59. Check yourself 3 of 3: what reaches the screen

Check

Find the quotation marks first, exactly as Python does.

print('Total: (12 items)')
LineWhat Python identifiesRole
1the outer parentheses mark the callstructure
1the quotation marks mark the messagestructure
1everything between the quotes is displayedcontent

Check your understanding

What appears on the screen?

  • A. Total: 12 items
  • B. Total: (12 items) (correct)
  • C. 'Total: (12 items)'
  • D. A syntax error from the unbalanced parentheses

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.

Why A tempts people
Drops the inner parentheses, which would only be right if they were structure. They are inside the quotes, so they are ordinary characters like the digits beside them.
Why C tempts people
Keeps the quotation marks in the output. Their job is to mark where the message begins and ends, and that job finishes before anything is displayed.
Why D tempts people
The parentheses are not unbalanced. The outer pair is matched, and the inner pair is inside a string, where Python does not read parentheses as syntax at all.

60. Where this shows up outside this course

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.

61. Confidence wager: commit before you check

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?

  • It prints three lines of text
  • It reports a syntax error
  • It runs successfully and produces no output
  • It refuses to run because the file contains no instructions

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.

62. Explain it to someone else

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.

63. Exit ticket

Exit ticket

One honest answer. It decides what the next lesson opens with.

Predict first

Which of these is still least solid for you?

  • What the word program actually means, precisely
  • The five categories, and telling which one a line belongs to
  • Decomposing a task until every piece is one of the five
  • Reading a transcript: telling what I typed from what the interpreter said

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.

64. Synthesis: draw the map of this lesson

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.

65. What you can do now

Recap

Five pages of a book, and the vocabulary for everything that follows.

If you remember one thingIt is this
From the definitionSequence. The order is part of the meaning, not part of the layout.
From the taxonomyFive categories, and every unfamiliar name is a combination of them.
From decompositionStop when each piece is one of the five — not when it feels simple.
From the interpreterThe prompt belongs to the machine. Never type it.
From Hello, WorldWhat 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

Sources

  1. Think Python, 2nd edition — Allen B. Downey — Allen B. Downey, Think Python: How to Think Like a Computer Scientist, 2nd edition (Green Tea Press, 2015), §1.1-1.3, pp. 1-3
  2. Python documentation — Whetting Your Appetite
  3. Python documentation — Using the Python Interpreter

Want this taught 1-on-1? Alexander tutors Python — $55/session, free consultation.

Book on Wyzant · Text (657) 465-8108