Reading Python
Before you start
You need nothing else first. This unit starts from scratch.
The idea in one paragraph
A Python program is a list of instructions that the computer runs from top to bottom. Six pieces cover
almost every snippet in these units: names that hold values, lists, for-loops, functions, import, and
square brackets that pick out parts of a list or array. This page teaches you to read those pieces, not to
write programs. Each section shows a few lines and what they print. Full courses are linked at the end.
A name holds a value, and = puts it there
An assignment such as count = 3 stores the value 3 under the name count.
The = sign means "store", not "is equal to". So count = count + 1 is not a contradiction.
It reads the old value, adds 1, and stores the result under the same name.
Values come in a few kinds. Whole numbers (3), decimal numbers (2.5), text in quotes
("cube", called a string), and True or False. The function
print shows values on the screen. Text after # is a comment: a note for people that
Python ignores.
names.py
count = 3
count = count + 1
name = "cube"
print(name, count)
cube 4
Arithmetic uses +, -, * (times), / (divide) and
** (power: 2 ** 3 is 8). The shortcut total += x means
total = total + x.
A list keeps values in order, numbered from 0
A list is several values in square brackets, separated by commas. Each value has a position, called its
index. Python counts positions from 0, so the first value is at index 0. A negative index counts from the
end: -1 is the last value.
xs[1:3] starts at index 1 and stops before
index 3, so it holds two values.A slice such as xs[1:3] picks a run of values. It starts at the first number and stops just
before the second. Leave a number out to go to the edge: xs[:2] is the first two values, and
xs[2:] is everything from index 2 on. The function len gives a list's length.
lists.py
xs = [4.0, 7.5, 1.0, 3.0]
print(xs[0], xs[2], xs[-1], len(xs))
print(xs[1:3])
4.0 1.0 3.0 4
[7.5, 1.0]
A for-loop repeats the indented lines once for each item
A for-loop takes the items of a list one at a time. On each pass, the name after for
holds the current item, and Python runs the indented lines below. The indentation, the spaces at the start
of a line, is how Python knows which lines belong to the loop. The first line that is not indented runs once, after
the loop ends.
Before you read the output, predict the last two lines it prints.
loop.py
total = 0
for x in [4.0, 7.5, 1.0]:
total = total + x
print("added", x, "total is now", total)
print("done")
added 4.0 total is now 4.0
added 7.5 total is now 11.5
added 1.0 total is now 12.5
done
range(n) gives the whole numbers 0, 1, ā¦, nā1, so for i in range(3): runs three times
with i equal to 0, 1 and 2. An if line works the same way: its indented lines run only when
its test is true. Tests use == (equal), != (not equal), < and
>.
A function gives a few lines a name, so you can run them again
A function is a named block of lines. def starts one. The names in parentheses are its
arguments: the values you hand it. return sends a value back and ends the function. You
call a function by writing its name followed by values in parentheses. In a def
line, an argument written as label="value" gets a default: the value it takes when a call
leaves it out. A call may also give its own value by name.
functions.py
def square(x):
return x * x
def describe(x, label="value"):
if x > 10:
return label + " is big"
return label + " is small"
print(square(3), square(2.5))
print(describe(30), describe(4, label="score"))
9 6.25
value is big score is small
describe(30) leaves label out, so it uses the default, "value".
describe(4, label="score") gives its own value, so the second answer starts with "score".
import brings in code that someone else wrote
A library is a collection of functions that you can load into your program. import math
loads the standard math library, and math.sqrt is its square-root function. The dot means
"the thing inside". import numpy as np loads NumPy, the library for arrays of numbers, under the short
name np. Units after this one use NumPy and PyTorch, a similar library for machine learning.
A dot after a value works the same way: pts.shape reads a property that the value carries, and
pts.sum() calls a function that belongs to it.
Square brackets with a comma pick rows and columns of a table
A list can hold lists. Then it works like a table: grid[1] is the second row, and
grid[1][0] is the first value in that row.
NumPy arrays let you write both indexes in one pair of brackets, separated by a comma: rows first, then columns.
A bare : means "every one". So pts[:, 0] means "every row, column 0": the first number of
every row. You will see this pattern often. Arrays in NumPy explains it fully.
Before you read the output, predict what pts[:, 0] prints.
tables.py
import math
import numpy as np
print(math.sqrt(16))
pts = np.array([[1, 2, 3],
[4, 5, 6]])
print(pts.shape)
print(pts[1])
print(pts[:, 0])
4.0
(2, 3)
[4 5 6]
[1 4]
The shape (2, 3) means 2 rows and 3 columns.
A few more pieces appear in later snippets
| You see | It means |
|---|---|
(2, 3) | A tuple: like a list, but it cannot change after it is made. |
a, b = 1, 2 | Two assignments at once: a gets 1 and b gets 2. |
for u, v in edges: | A loop over a list of pairs. On each pass, u and v get the two values of one pair. zip(xs, ys) pairs up two lists value by value, and enumerate(xs) pairs each value with its index. |
None | A value that means "nothing yet". |
{"axis": 0} | A dictionary: values looked up by a name. d["axis"] gives 0. |
[x * 2 for x in xs] | A new list built by a loop in one line: here, every value of xs doubled. |
sum(xs) | The total of the numbers in the list xs. |
round(x, 3) | The number x, rounded to 3 decimal places. |
f"loss {x:.2f}" | An f-string: text in which each pair of braces is replaced by a value. :.2f shows the value with 2 decimal places, and :6.2f also pads it to at least 6 characters, so that columns line up. |
1_000_000 | One million. Python ignores the underscores; they only help you read. |
with ...: | Run the indented lines inside a setting, and undo the setting afterward. |
np.sqrt(xs),np.round(xs, 3) | NumPy's versions of math functions, such as np.sqrt, np.exp, np.log, np.sin, np.cos, np.abs and np.round. Each one works on every number in the array xs at once. |
xs.mean(),xs.std(),xs.max() | The mean, the standard deviation and the largest value of all the numbers in xs. Arrays in NumPy shows how axis gives one value per row or column instead. |
xs.sum(axis=1, keepdims=True) | The total of each row, kept as a column: shape (n, 1) instead of (n,). Then xs / xs.sum(axis=1, keepdims=True) divides each row by its own total. PyTorch spells it keepdim=True. |
rng = np.random. | A generator of random numbers, started from the seed 0. rng.normal(size=5) then draws 5 numbers from a bell curve, and rng.integers(1, 7) draws a whole number from 1 to 6. Random draws explains seeds. |
It skips classes, errors and how to handle them, files, and many other parts of the language. It also skips details such as the difference between whole numbers and decimals in division. That is enough for reading short snippets. To write your own programs, take one of the courses below.
Check yourself
-
After
xs = [10, 20, 30, 40, 50], what arexs[1],xs[-2]andxs[1:4]?Answer
20,40and[20, 30, 40]. Indexes count from 0,-2is the second from the end, and the slice stops before index 4. -
What does this print?
n = 0 for x in [3, 1, 4]: n = n + 1 print(n)Answer
3. The loop runs once per item and adds 1 each time. Theprintline is not indented, so it runs once, after the loop. -
An array
ptshas shape(5, 3): five points, each with x, y and z. Which expression gives every point's z value:pts[2],pts[:, 2]orpts[2, :]?Answer
pts[:, 2]: every row, column 2. The other two both give row 2, which is the third point.
Go further
Optional background, for when you want to write Python, not only read it.
-
The official tutorial. Its next chapter, More Control Flow Tools, covers loops and functions.
-
A free course with videos, a book and exercises, written for people who have never programmed.
-
A fast tour of Python aimed at scientists, followed by chapters on NumPy.
Where this shows up
Units that build on this one
- Arrays in NumPy Intermediate
- Gradient clipping Intermediate
- Learning-rate schedules: warm-up, decay Intermediate
- Data loaders: preparing examples in parallel Intermediate
- Checkpoints: saving training to resume it Intermediate
- Recursion: a function that calls itself Intermediate