A First Taste of Algorithms

Lab 0: Talking to the Machine

✦ ✦ ✦

Before Chapter 1. Ten minutes, maybe fifteen.

Every lab in this book asks you to run small programs and watch what they do. This one exists so that the first time is now, when nothing is at stake, rather than later, when something is.

You need a place to run Python. Any of these works: the editor at python.org, an installed copy of Python, or a notebook environment. It does not matter which. The programs in this book use nothing but Python itself — no packages to install, nothing that will stop working in five years. If a program here fits on one screen, it is meant to be typed, not copied. Typing is slower. That is the point.

1. The machine repeats what you say

Type this and run it:

print("hello")

The machine prints hello. This is the whole transaction: you write an instruction, the machine carries it out, exactly, and nothing more. It does not know what you meant. It knows what you wrote. The entire craft of programming lives in that gap, and this book is partly about learning to feel the gap before the machine shows it to you.

2. The machine does arithmetic

print(3 + 4)
print(3 * 4)
print(2 ** 10)

The last line is 2 to the 10th power. Run it. Then change it to 2 ** 100 and run it again. That number has thirty-one digits. The machine did not slow down. Hold on to this: the machine is not smart, but it is fast, and almost everything in this book comes from asking what fast-but-not-smart is good for.

3. The machine remembers what you name

steps = 0
steps = steps + 1
steps = steps + 1
print(steps)

A variable is a name attached to a value. The line steps = steps + 1 looks wrong if you read = as it is read in mathematics — no number equals itself plus one. In Python, = is not a statement of fact. It is an instruction: compute the thing on the right, then attach the name on the left to it. Read it as “steps becomes steps plus one” and it is sensible.

This little program is a counter. In Chapter 1 we will count something worth counting.

All 32 chapters of A First Taste of Algorithms · Foundations · All courses