QueryCasequerycase.com
Lab reference guide

Python Cheat Sheet

The Python you need, right when you need it. Find a pattern, copy an example, and get back to the case.

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.

One example, all the moving parts
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 back
01

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

Pattern
name = value
Example
bags = 26
total = 29778
per_bag = total / bags
round(per_bag, 2)  # → 1145.31

Numbers and text

Whole numbers (int), decimals (float) and text (str), which goes in quotes. int() and str() turn one into the other.

Example
count = 12
rate = 2.5
name = "Hollis"
int("42") + 1  # → 43
"Case " + str(7)  # → Case 7

Arithmetic

+ - * / as you would expect. // divides and drops the remainder, % gives only the remainder, and ** is a power.

Example
7 / 2  # → 3.5
7 // 2  # → 3
7 % 2  # → 1
2 ** 3  # → 8

len, 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.

Example
temps = [4, 3, 6, 2]
len(temps)  # → 4
sum(temps)  # → 15
max(temps)  # → 6
min(temps)  # → 2
round(15 / 4, 1)  # → 3.8

Calling a function

The function's name, then round brackets holding what it works on. The brackets are what run it.

Pattern
function(argument)
Example
guests = ["Ade", "Bo", "Cy"]
len(guests)  # → 3
TipWithout the brackets you have the function itself, not its answer: len on its own shows <built-in function len>.
02

Lists

Visual reference

Every item has two addresses: from the front, counting from 0, and from the back, counting from -1.

[0]Ash[-4]
[1]Bea[-3]
[2]Cal[-2]
[3]Dee[-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.

Example
statements = ["Ash", "Bea", "Cal", "Dee"]
len(statements)  # → 4

Indexing from 0

A position in square brackets picks one item out. Positions count from 0, so the first item is [0].

Pattern
items[position]
Example
statements = ["Ash", "Bea", "Cal", "Dee"]
statements[0]  # → Ash
statements[2]  # → Cal
TipThe third item is [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.

Example
statements = ["Ash", "Bea", "Cal", "Dee"]
statements[-1]  # → Dee
statements[-2]  # → Cal

Slicing

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.

Pattern
items[start:stop]
Example
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.

Example
flagged = []
flagged.append("bag 7")
flagged.append("bag 12")
len(flagged)  # → 2

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

Example
statements = ["Ash", "Bea", "Cal"]
"Bea" in statements  # → True
sorted([30, 4, 12])  # → [4, 12, 30]
03

Decisions

Comparisons

== equal, != not equal, < > <= >=. Every comparison gives back True or False.

Example
limit = 4
5 > limit  # → True
5 == limit  # → False
"OPEN" != "SHUT"  # → True
TipOne = 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.

Pattern
if test:
    when_true
else:
    when_false
Example
temp = 6
if temp > 4:
    verdict = "INADMISSIBLE"
else:
    verdict = "ADMISSIBLE"
verdict  # → INADMISSIBLE

elif

More than two outcomes: each elif is checked only if everything above it was False, and the first True one wins.

Example
level = 70
if level >= 85:
    band = "Breach"
elif level >= 65:
    band = "Loud"
else:
    band = "Quiet"
band  # → Loud
TipAsk about the biggest threshold first. Start at the low end and every value lands in the first test.

and, or, not

and needs both tests True, or needs either, and not flips True and False.

Example
door = "OPEN"
hour = 2
door == "OPEN" and hour < 6  # → True
door == "SHUT" or hour < 6  # → True
not hour < 6  # → False
04

Loops

for

Runs the indented lines once for every item, with the loop name holding a different item each time round.

Pattern
for item in items:
    do_something(item)
Example
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.

Example
checks = ["OPEN", "SHUT", "OPEN", "SHUT"]
open_count = 0
for check in checks:
    if check == "OPEN":
        open_count = open_count + 1
open_count  # → 2
TipSet the starting value above the loop. Set it inside and it goes back to 0 every turn.

A running total

The same shape, adding each item instead of 1. total += amount is the short way to write total = total + amount.

Example
total = 0
for amount in [120, 80, 300]:
    total = total + amount
total  # → 500

Building a list in a loop

An empty list before the loop, and .append() inside it for every item worth keeping.

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

Example
list(range(4))  # → [0, 1, 2, 3]
for i in range(3):
    print("round", i)
05

Dictionaries

A dictionary

Keys and their values in curly brackets. Look a value up by its key in square brackets.

Pattern
{"key": value, "other": value}
Example
bag = {"owner": "Rasheed", "logged": 420, "sealed_at": 400}
bag["owner"]  # → Rasheed

Adding or changing a key

Assign to a key: a new key is added, an existing one is replaced.

Example
bag = {"logged": 420, "sealed_at": 400}
bag["gap"] = bag["logged"] - bag["sealed_at"]
bag["gap"]  # → 20

A list of dictionaries

One dictionary per record, the shape most data arrives in. A position picks the record, then a key picks the field.

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

Example
totals = {"North": 400}
totals.get("North", 0)  # → 400
totals.get("South", 0)  # → 0
Tiptotals["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.

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

Example
tally = {"North": 2, "South": 1}
for station, count in tally.items():
    print(station, count)
06

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.

Pattern
def name(inputs):
    return answer
Example
def difference(tin):
    return tin["counted"] - tin["expected"]

difference({"counted": 180, "expected": 200})  # → -20

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

Example
def given(x):
    return x

given(5) + 1  # → 6
TipA function that prints instead of returning looks right on screen and breaks the moment its answer is used.

Calling your own function

Once it is defined, it is called like any other: inside an if, inside a loop, anywhere a value goes.

Example
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  # → 1
07

Text and Files

Reading a file

open("name").read() gives the whole file back as one piece of text.

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

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

Example
minutes = int("75")
minutes > 60  # → True

Text methods

.strip() takes spaces off both ends, .lower() and .upper() change the case, .replace() swaps one piece of text for another.

Example
"  Harbour ".strip()  # → Harbour
"VYPER".lower()  # → vyper
"£1,250".replace(",", "")  # → £1250

Every line of a file

Split the file into lines, skip the header with [1:], and split each line into its fields inside a loop.

Example
total = 0
for line in open("swipes.csv").read().split("\n")[1:]:
    parts = line.split(",")
    total = total + int(parts[2])
total  # → 87
08

Errors Decoded

ErrorWhat it meansFirst thing to check
NameErrorPython has nothing stored under that name.The spelling, and that the line which makes it has run.
TypeError: not subscriptableSquare brackets on a function.Functions take round brackets: max(temps), not max[temps].
IndexErrorA position past the end of the list.Positions count from 0: a list of five ends at [4].
KeyErrorThe dictionary has no such key.The spelling, or use .get(key, default).
IndentationErrorA line ending in : has nothing indented under it.Four spaces in, on every line of the block.
SyntaxErrorPython cannot read the line at all.A missing :, bracket or quote, or = where == was meant.
AttributeErrorThe 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.

09

From Lists to Tables

The pandas cheat sheet

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.

Example
import pandas as pd
df = pd.read_csv("swipes.csv")
len(df)  # → 2
df["minutes"].sum()  # → 87

A total for each group

groupby splits the table by one column and totals another for each group: the tally dictionary, in one line.

Example
import pandas as pd
df = pd.read_csv("swipes.csv")
df.groupby("door")["minutes"].sum()
Python Cheat Sheet · QueryCaseThe full course is at querycase.com