Appendices

Appendix B

Python Quick Reference

Page 439 of the printed book · 12 sections

Everything on these pages is explained properly in the chapters. This is the “I know I’ve seen it somewhere” version.

#Values and variables

Python
1name = "Sara"            # str  (text)
2age = 29                 # int  (whole number)
3height = 1.68            # float (decimal)
4member = True            # bool (True or False)
5nothing = None           # no value at all
6
7type(age)                # <class 'int'>
8int("42"), float("3.5"), str(42)    # converting

#Text

Python
1f"{name} is {age}"       # f-string
2f"{price:.2f}"           # two decimal places
3len(name)                # 4
4name.upper(), name.lower(), name.title()
5name.strip()             # remove spaces at both ends
6name.replace("a", "o")
7name.split(",")          # text -> list
8", ".join(names)         # list -> text
9name.startswith("S"), name.endswith(".py")
10"ar" in name             # True
11name[0], name[-1], name[1:3]

#Arithmetic and comparison

Python
17 + 2, 7 - 2, 7 * 2, 7 / 2     # 9 5 14 3.5
27 // 2, 7 % 2, 7 ** 2          # 3 1 49
3round(3.14159, 2)              # 3.14
4==  !=  <  <=  >  >=           # comparisons
5and  or  not                   # combining them

#Decisions and loops

Python
1if score >= 80:
2    print("great")
3elif score >= 50:
4    print("pass")
5else:
6    print("try again")
7
8for item in items:
9    print(item)
10
11for i in range(5):             # 0, 1, 2, 3, 4
12    print(i)
13
14for i, item in enumerate(items, start=1):
15    print(i, item)
16
17while count > 0:
18    count -= 1
19
20break                          # leave the loop now
21continue                       # skip to the next round

#Lists, tuples, dictionaries and sets

Python
1items = ["a", "b", "c"]
2items.append("d"); items.remove("a"); items.sort()
3items[0], items[-1], items[1:3], len(items)
4point = (3, 4)                       # tuple: can't change
5phones = {"Ana": "0412", "Raj": "0499"}
6phones["Zoe"] = "0455"               # add or change
7phones.get("Tom", "unknown")         # safe lookup
8for name, number in phones.items():
9    print(name, number)
10seen = {"red", "blue"}               # set: no duplicates
11seen.add("red")                      # still two items
12squares = [n * n for n in range(5)]  # list comprehension

#Functions

Python
1def area(width, height=1):
2    """Return the area of a rectangle."""
3    return width * height
4
5area(3, 4)
6area(width=3)                  # height uses its default

#Errors

Python
1try:
2    age = int(text)
3except ValueError:
4    print("Please type a number.")
5else:
6    print("Thanks")
7finally:
8    print("This always runs")
9
10raise ValueError("age must be positive")

#Files and folders

Python
1from pathlib import Path
2
3HERE = Path(__file__).parent
4path = HERE / "data" / "notes.txt"
5text = path.read_text(encoding="utf-8")
6path.write_text("hello\n", encoding="utf-8")
7
8with open(path, "a", encoding="utf-8") as f:
9    f.write("one more line\n")
10
11path.exists(), path.name, path.stem, path.suffix
12for p in HERE.glob("*.csv"):
13    print(p.name)

#Classes

Python
1class Remote:
2    MAX_VOLUME = 100                 # class variable
3
4    def __init__(self, name):        # factory settings
5        self.name = name             # instance variable
6        self.volume = 10
7
8    def volume_up(self):             # a method
9        self.volume += 1
10
11    def __str__(self):               # used by print()
12        return f"{self.name}: {self.volume}"
13
14bedroom = Remote("Bedroom")          # an object
15bedroom.volume_up()

#Modules

Python
1import math                    # use as math.sqrt(16)
2from random import choice      # use as choice(items)
3import pandas as pd            # a short nickname
4
5if __name__ == "__main__":     # only when run directly
6    main()

#Terminal commands

TaskWindowsmacOS and Linux
Which Python?python --version or py --versionpython3 --version
Run a scriptpython hello.pypython3 hello.py
Where am I?cdpwd
List filesdirls
Go into a foldercd python-projectscd python-projects
Go up one foldercd ..cd ..
Make a virtual environmentpython -m venv .venvpython3 -m venv .venv
Switch it on.venv\Scripts\activatesource .venv/bin/activate
Switch it offdeactivatedeactivate
Install a packagepython -m pip install requestspython3 -m pip install requests
Save your package listpip freeze > requirements.txtpip freeze > requirements.txt
Install from the listpip install -r requirements.txtpip install -r requirements.txt
Stop a running programCtrl+CCtrl+C

#VS Code shortcuts

TaskWindows and LinuxmacOS
Command PaletteCtrl+Shift+PCmd+Shift+P
Choose which PythonCommand Palette, then Python: Select Interpreterthe same
Open or close the terminalCtrl and the backtick keyCtrl and the backtick key
SaveCtrl+SCmd+S
Comment or uncomment linesCtrl+/Cmd+/
Find in this fileCtrl+FCmd+F
Rename a variable everywhereF2F2
Start debuggingF5F5
Zoom in or outCtrl+= and Ctrl+-Cmd+= and Cmd+-