Each card gives a pattern (the template) and an example with what comes back after # →. Words in a pattern like name and value are placeholders: swap in your own.
temps = [4, 3, 6, 2]
warmest = max(temps)
if warmest > 4:
print("Too warm:", warmest)temps is a list, max is a function that takes it in round brackets, and the indented line only runs when the test above it is True.
forkeywordslenbuilt-in functions"text"text42numbers# → 3what comes backValues and Names
Variables
A name holds a value. = puts the value on the right into the name on the left, and the name can be used from then on.
name = valuebags = 26
total = 29778
per_bag = total / bags
round(per_bag, 2) # → 1145.31Numbers and text
Whole numbers (int), decimals (float) and text (str), which goes in quotes. int() and str() turn one into the other.
count = 12
rate = 2.5
name = "Hollis"
int("42") + 1 # → 43
"Case " + str(7) # → Case 7Arithmetic
+ - * / as you would expect. // divides and drops the remainder, % gives only the remainder, and ** is a power.
7 / 2 # → 3.5
7 // 2 # → 3
7 % 2 # → 1
2 ** 3 # → 8len, sum, max, min, round
The built-in functions every case leans on: how many, the total, the biggest, the smallest, and a number rounded to so many places.
temps = [4, 3, 6, 2]
len(temps) # → 4
sum(temps) # → 15
max(temps) # → 6
min(temps) # → 2
round(15 / 4, 1) # → 3.8Calling a function
The function's name, then round brackets holding what it works on. The brackets are what run it.
function(argument)guests = ["Ade", "Bo", "Cy"]
len(guests) # → 3len on its own shows <built-in function len>.Lists
Visual reference
Every item has two addresses: from the front, counting from 0, and from the back, counting from -1.
The slice [1:3] starts at position 1 and stops BEFORE position 3.
A list
Values in square brackets, in order, separated by commas. A list can hold numbers, text, or both.
statements = ["Ash", "Bea", "Cal", "Dee"]
len(statements) # → 4Indexing from 0
A position in square brackets picks one item out. Positions count from 0, so the first item is [0].
items[position]statements = ["Ash", "Bea", "Cal", "Dee"]
statements[0] # → Ash
statements[2] # → Cal[2]. Counting from 1 is the most common slip in the first week.Negative indexing
Negative positions count from the end: [-1] is the last item, [-2] the one before it.
statements = ["Ash", "Bea", "Cal", "Dee"]
statements[-1] # → Dee
statements[-2] # → CalSlicing
A start and a stop with a colon between them give back a new list. The stop position is NOT included; leave either side out to run to the end.
items[start:stop]statements = ["Ash", "Bea", "Cal", "Dee"]
statements[1:3] # → ['Bea', 'Cal']
statements[:2] # → ['Ash', 'Bea']
statements[-2:] # → ['Cal', 'Dee'].append()
Adds one item to the end of a list, changing the list itself. Start from an empty list, [], to build one up.
flagged = []
flagged.append("bag 7")
flagged.append("bag 12")
len(flagged) # → 2in and sorted
in asks whether a value is in the list. sorted() gives back a new list in order, smallest first, and leaves the old one alone.
statements = ["Ash", "Bea", "Cal"]
"Bea" in statements # → True
sorted([30, 4, 12]) # → [4, 12, 30]Decisions
Comparisons
== equal, != not equal, < > <= >=. Every comparison gives back True or False.
limit = 4
5 > limit # → True
5 == limit # → False
"OPEN" != "SHUT" # → True= stores a value in a name. Asking whether two things are the same needs two: ==.if and else
A test, a colon, and the lines to run when it is True, indented four spaces under it. else: runs when it is False.
if test:
when_true
else:
when_falsetemp = 6
if temp > 4:
verdict = "INADMISSIBLE"
else:
verdict = "ADMISSIBLE"
verdict # → INADMISSIBLEelif
More than two outcomes: each elif is checked only if everything above it was False, and the first True one wins.
level = 70
if level >= 85:
band = "Breach"
elif level >= 65:
band = "Loud"
else:
band = "Quiet"
band # → Loudand, or, not
and needs both tests True, or needs either, and not flips True and False.
door = "OPEN"
hour = 2
door == "OPEN" and hour < 6 # → True
door == "SHUT" or hour < 6 # → True
not hour < 6 # → FalseLoops
for
Runs the indented lines once for every item, with the loop name holding a different item each time round.
for item in items:
do_something(item)for check in ["OPEN", "SHUT", "OPEN"]:
print(check)Counting in a loop
Start a count at 0 BEFORE the loop, then add 1 inside it whenever an item passes the test.
checks = ["OPEN", "SHUT", "OPEN", "SHUT"]
open_count = 0
for check in checks:
if check == "OPEN":
open_count = open_count + 1
open_count # → 2A running total
The same shape, adding each item instead of 1. total += amount is the short way to write total = total + amount.
total = 0
for amount in [120, 80, 300]:
total = total + amount
total # → 500Building a list in a loop
An empty list before the loop, and .append() inside it for every item worth keeping.
values = [120, 450, 80]
big = []
for value in values:
if value > 100:
big.append(value)
big # → [120, 450]range()
range(n) counts from 0 up to n, not including n. The way to run something a set number of times.
list(range(4)) # → [0, 1, 2, 3]
for i in range(3):
print("round", i)Dictionaries
A dictionary
Keys and their values in curly brackets. Look a value up by its key in square brackets.
{"key": value, "other": value}bag = {"owner": "Rasheed", "logged": 420, "sealed_at": 400}
bag["owner"] # → RasheedAdding or changing a key
Assign to a key: a new key is added, an existing one is replaced.
bag = {"logged": 420, "sealed_at": 400}
bag["gap"] = bag["logged"] - bag["sealed_at"]
bag["gap"] # → 20A list of dictionaries
One dictionary per record, the shape most data arrives in. A position picks the record, then a key picks the field.
bags = [{"owner": "Ann", "value": 40}, {"owner": "Bo", "value": 95}]
bags[1]["owner"] # → Bo.get() with a default
Looks a key up, and gives back the default instead of raising an error when the key is not there.
totals = {"North": 400}
totals.get("North", 0) # → 400
totals.get("South", 0) # → 0totals["South"] raises a KeyError. .get("South", 0) says 0 and carries on.A dictionary as a tally
Count things by name: each key is a thing, each value how many times it was seen.
tally = {}
for station in ["North", "South", "North"]:
tally[station] = tally.get(station, 0) + 1
tally # → {'North': 2, 'South': 1}.items()
Walks a dictionary a pair at a time: the key, then its value.
tally = {"North": 2, "South": 1}
for station, count in tally.items():
print(station, count)Functions
def and return
A function is a named recipe: def, its name, what goes in, and a colon. return hands the answer back to whoever called it.
def name(inputs):
return answerdef difference(tin):
return tin["counted"] - tin["expected"]
difference({"counted": 180, "expected": 200}) # → -20return versus print
return gives a value back that the next line can use. print only shows it on screen, and the call itself gives back None.
def given(x):
return x
given(5) + 1 # → 6Calling your own function
Once it is defined, it is called like any other: inside an if, inside a loop, anywhere a value goes.
def is_short(tin):
return tin["counted"] < tin["expected"]
tins = [{"counted": 50, "expected": 50}, {"counted": 30, "expected": 50}]
short = 0
for tin in tins:
if is_short(tin):
short = short + 1
short # → 1Text and Files
Reading a file
open("name").read() gives the whole file back as one piece of text.
text = open("swipes.csv").read()
text[:9] # → name,door.split()
Cuts text into a list at every separator: "\n" for lines, "," for the fields of a CSV line.
text = open("swipes.csv").read()
lines = text.split("\n")
len(lines) # → 3
lines[-1].split(",") # → ['Bea', 'office', '75']Text into numbers
Everything read from a file is text. int() and float() turn number-shaped text into numbers you can compare and add.
minutes = int("75")
minutes > 60 # → TrueText methods
.strip() takes spaces off both ends, .lower() and .upper() change the case, .replace() swaps one piece of text for another.
" Harbour ".strip() # → Harbour
"VYPER".lower() # → vyper
"£1,250".replace(",", "") # → £1250Every line of a file
Split the file into lines, skip the header with [1:], and split each line into its fields inside a loop.
total = 0
for line in open("swipes.csv").read().split("\n")[1:]:
parts = line.split(",")
total = total + int(parts[2])
total # → 87Errors Decoded
| Error | What it means | First thing to check |
|---|---|---|
| NameError | Python has nothing stored under that name. | The spelling, and that the line which makes it has run. |
| TypeError: not subscriptable | Square brackets on a function. | Functions take round brackets: max(temps), not max[temps]. |
| IndexError | A position past the end of the list. | Positions count from 0: a list of five ends at [4]. |
| KeyError | The dictionary has no such key. | The spelling, or use .get(key, default). |
| IndentationError | A line ending in : has nothing indented under it. | Four spaces in, on every line of the block. |
| SyntaxError | Python cannot read the line at all. | A missing :, bracket or quote, or = where == was meant. |
| AttributeError | The value has no method by that name. | The spelling, or a call missing its (). |
| ValueError: invalid literal for int() | int() was given text that is not a whole number. | Spaces, commas or a decimal point in the text. |
On the bench every error comes with a line under it saying what went wrong in plain words.
From Lists to Tables
pandas and read_csv
pandas reads a CSV straight into a table, a DataFrame, with the header as its column names. The loop above, done in a line.
import pandas as pd
df = pd.read_csv("swipes.csv")
len(df) # → 2
df["minutes"].sum() # → 87A total for each group
groupby splits the table by one column and totals another for each group: the tally dictionary, in one line.
import pandas as pd
df = pd.read_csv("swipes.csv")
df.groupby("door")["minutes"].sum()