Values and names
Write a small program that transforms data using conditions, loops and functions.
THE IDEA
A program changes state, one line at a time
A program is a list of instructions that Python carries out from top to bottom. The thing that changes as it goes is state: which values exist and which names refer to them. To read a program you do not guess what the code "sounds like". You track the state after each line, the way you will do in the board below.
The line x = 4 is an assignment. It is not a maths equation. It means: make the number 4, then attach the name x to it. A name is a label, and a value is the thing the label is stuck on.
Program (line 0 of 3)
x = 4y = xx = 7Names
no names yet
Objects in memory
no objects yet
Nothing has happened yet. No names, no objects.
Reassigning moves the label, it does not edit the value
After y = x, both names point at the same object. When you later write x = 7, Python does not reach into the 4 and change it. It makes (or finds) a 7 and moves the label x over. The name y never moved, so it still sees 4.
Predict first. After x = 4, y = x and x = 7, what is y?
Values have types, and types decide what an operation does
Every value has a type. The four you meet first are int (whole numbers), float (numbers with a fraction), str (text) and bool (True or False). The same symbol can mean different things for different types, so always ask what type you are holding.
3 + 4 gives 7
Type of the result: int
Whole numbers add like you expect.
Predict first. A form gives you price = "20" (text). What does price * 3 give?
The classic mistake: mixing text and numbers
age = 30
message = "I am " + age + " years old"
# TypeError: can only concatenate str (not "int") to str
message = "I am " + str(age) + " years old" # works: I am 30 years oldConvert on purpose: int(...), float(...), str(...).
Expect Python to guess whether "3" + 4 means 7 or "34". It refuses.
Chapter context
A program is a precise sequence of state changes. Python names refer to objects; reading a program means tracking the values those names refer to, rather than guessing from how the code sounds.
TRY IT YOURSELF
Exercise 1: swap two names
aandbpoint at two numbers. Make them trade places, soaends up pointing at 3 andbat 10.- Writing
a = bfirst loses the old value ofa. Park it under a third name,temp, before you overwrite anything. - Press Run and check. Your program is also run again with different starting numbers, so typing 3 and 10 directly will not pass.
Exercise 2: text is not a number
pricecame out of a web form, so it is the text"20", not the number 20.- Fill in the three TODO lines. Convert with
int(...), divide with/, and turn a number back into text withstr(...).
Both exercises must be solved to finish this lesson.
Stuck, or something not working? You can come back to it any time.
CHECK YOUR UNDERSTANDING
Predict x after x = 4; y = x; x = 7.
Chapter reference: math, worked example & code
This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.
Math and notation
For an accumulator over numbers :
The subscript denotes a step, not a Python index. After the last step, is the sum. For a mean, divide by the number of items, and define what should happen for an empty list.
Worked example
Trace a robot's forward distances [2, 1, 3]. Position starts at zero and changes to 2, then 3, then 6. Replacing three copy-pasted moves with a loop preserves the order and final state. A mean distance is 6/3 = 2; the count is 3, not the last list index 2.
Reference code
The following example uses the Python standard library and does not call a remote service.
moves = [2, 1, 3]
position = 0
for distance in moves:
position += distance
assert position == 6
assert sum(moves) / len(moves) == 2
Python examples are provided for study and local execution; this page does not execute Python.
Common mistakes
Assignment does not copy a mutable object. A loop stop value is exclusive. A function can return None even when its print output looks correct.