Cheatsheets
Quick, printable reference tables for every major topic in the course.
Syntax & Variables
| Syntax | What it does |
|---|---|
x = 5 | Assign the value 5 to the name x |
x, y = 1, 2 | Assign multiple variables in one line |
type(x) | Get the type of a value |
# comment | A single-line comment, ignored by Python |
"""docstring""" | A multi-line string, often used to document functions |
Numbers & Operators
| Syntax | What it does |
|---|---|
+ - * / | Addition, subtraction, multiplication, division |
// | Floor (whole-number) division |
% | Modulo — the remainder of division |
** | Exponent (power) |
round(x, 2) | Round x to 2 decimal places |
Strings
| Syntax | What it does |
|---|---|
f"{name} is {age}" | f-string — embed variables in text |
s[0], s[-1] | First character, last character |
s[1:4] | Slice from index 1 up to (not including) 4 |
s.strip() | Remove leading/trailing whitespace |
s.upper() / s.lower() | Convert case |
s.split(',') | Split into a list on a separator |
s.replace(a, b) | Replace all occurrences of a with b |
Lists
| Syntax | What it does |
|---|---|
lst.append(x) | Add x to the end |
lst.insert(i, x) | Insert x at index i |
lst.remove(x) | Remove the first occurrence of x |
lst.pop() | Remove and return the last item |
lst.sort() | Sort the list in place |
len(lst) | Number of items |
x in lst | Membership test |
Dictionaries
| Syntax | What it does |
|---|---|
d["key"] | Look up a value by key (raises KeyError if missing) |
d.get("key", default) | Safe lookup with a fallback |
d.items() | Loop over (key, value) pairs |
d.keys() / d.values() | Just the keys, or just the values |
"key" in d | Check whether a key exists |
Control Flow
| Syntax | What it does |
|---|---|
if / elif / else | Branch based on a condition |
for x in iterable: | Loop over a known sequence |
while condition: | Loop until a condition becomes False |
break | Exit the loop immediately |
continue | Skip to the next iteration |
Functions & Lambdas
| Syntax | What it does |
|---|---|
def f(a, b=1): | Define a function with a default parameter |
return value | Send a value back to the caller |
lambda x: x * 2 | A small, unnamed inline function |
*args | Collect extra positional arguments into a tuple |
**kwargs | Collect extra keyword arguments into a dictionary |
OOP
| Syntax | What it does |
|---|---|
class Dog: | Define a class |
def __init__(self, name): | The constructor, run when an object is created |
self.name = name | Set an instance attribute |
class Dog(Animal): | Inherit from a superclass |
@property | Make a method callable like a plain attribute |
Exceptions
| Syntax | What it does |
|---|---|
try / except ValueError: | Catch a specific error type |
except Exception as e: | Catch an error and inspect its message |
else: | Runs only if no exception occurred |
finally: | Always runs, error or not |
raise ValueError("msg") | Deliberately trigger an exception |
File I/O
| Syntax | What it does |
|---|---|
open("f.txt", "r") | Open for reading (default mode) |
open("f.txt", "w") | Open for writing (overwrites existing content) |
open("f.txt", "a") | Open for appending |
with open(...) as f: | Automatically closes the file afterward |
f.read() / f.readlines() | Read whole file, or as a list of lines |
SQL (SQLite)
| Syntax | What it does |
|---|---|
sqlite3.connect('app.db') | Open (or create) a database file |
cursor.execute(sql, params) | Run a query safely with ? placeholders |
conn.commit() | Save INSERT/UPDATE/DELETE changes |
cursor.fetchall() | Get every row from a SELECT as a list of tuples |
WHERE ... ORDER BY ... | Filter rows, then sort them |