LEARN TO CODE | QUICK REFERENCE
PYTHON CHEAT SHEET
Syntax, built-in functions and popular methods at a glance. Covers course sections 1, 2, 3, 4 and 6 only.
JUMP TO A TOPIC
Examples target Python 3.10 or later. Each row is an independent snippet: read it on its own rather than pasting every row together. Use the bookmark links to find what you need.
SECTION 1 | OUTPUT, VARIABLES AND TYPES
| Item | Use and example |
|---|---|
| print() |
Display one or more values.
|
| Comments |
Explain a reason or assumption.
|
| Assignment |
Bind a name to a value; = does not compare.
|
| Constants |
UPPER_CASE names signal intended constants.
|
| int / float |
Whole-number / floating-point values.
|
| str / bool / None |
Text / logical value / absence of a value.
|
| type() / isinstance() |
Inspect a type / test type membership.
|
| input() |
Read text from the user; returns str.
|
| int() / float() / str() |
Convert values; unsuitable text raises ValueError.
|
| bool() |
Empty collections/strings, zero and None are falsy.
|
| f-strings |
Insert expression values into text.
|
| Formatting numbers |
Format for display; the result is text.
|
Use four spaces for each indentation level. Python names are case-sensitive. Input conversion alone is not full validation.
SECTION 1 | ARITHMETIC AND NUMBERS
| Item | Use and example |
|---|---|
| + - * / |
Addition, subtraction, multiplication and division.
|
| // |
Floor division: rounds down, not towards zero.
|
| % |
Remainder; useful for even/odd checks.
|
| ** |
Exponentiation. Use parentheses for clear grouping.
|
| += -= *= /= |
Calculate from the current value and reassign.
|
| abs() / round() |
Magnitude / numeric rounding.
|
| min() / max() / sum() |
Smallest, largest and total in numeric data.
|
| Average |
Check for an empty collection before dividing.
|
Floating-point arithmetic is approximate. round() uses ties-to-even for exact ties; binary representation can affect decimal-looking rounding cases.
SECTION 2 | CONDITIONS AND BOOLEAN LOGIC
| Item | Use and example |
|---|---|
| Comparison operators |
==, !=, <, <=, > and >= compare values.
|
| and / or / not |
Combine conditions or reverse a truth value.
|
| if / elif / else |
Run the first matching branch.
|
| Chained comparisons |
A readable inclusive range check.
|
| in / not in |
Test membership; dictionary membership tests keys.
|
| is None |
Test absence with identity, not a string.
|
| Conditional expression |
Choose one of two expression values.
|
Use == for value equality. Use is for identity checks such as is None. and/or return operand values, not always bool values.
SECTION 2 | LOOPS AND LOOP CONTROL
| Item | Use and example |
|---|---|
| for |
Repeat for each item in an iterable.
|
| range(stop) |
Integers starting at 0; stop is excluded.
|
| range(start, stop, step) |
Choose the start and step; stop stays excluded.
|
| while |
Check a condition before each pass.
|
| break |
Exit the nearest loop immediately.
|
| continue |
Skip the rest of this pass.
|
| enumerate() |
Get an index/count and a value together.
|
| zip() |
Pair iterables; normally stops at the shortest.
|
| Totalling / counting |
Initialise once outside the loop body.
|
The loop body is its indented repeated code. A while loop needs a route to a false condition or break; avoid accidental infinite loops.
SECTION 2 | TRACING AND DEBUGGING
| Item | Use and example |
|---|---|
| Labelled output |
Inspect values at the step being investigated.
|
| breakpoint() |
Pause in a configured debugger; usually pdb by default.
|
| Syntax / runtime / logic |
Parse failure / operation failure / wrong result.
|
| Boundary tests |
Check just below, on and above a threshold.
|
In VS Code, set an editor breakpoint and use the Python debugger to step and inspect variables. In IDLE, save the file and use Run Module (F5).
SECTION 3 | STRINGS AND SLICING
| Item | Use and example |
|---|---|
| Indexing |
First character is index 0; -1 is the last.
|
| Slicing |
start included, stop excluded; step is optional.
|
| len() |
Count string code points, not displayed glyphs.
|
| lower() / upper() |
Return case-converted strings.
|
| strip() |
Remove surrounding whitespace by default.
|
| replace() |
Return a string with occurrences replaced.
|
| split() |
Return a list split by whitespace or a separator.
|
| join() |
Join an iterable of strings with a separator.
|
| find() / index() |
First match: find returns -1 if absent; index raises.
|
| count() |
Count non-overlapping occurrences.
|
| startswith() / endswith() |
Test a prefix or suffix.
|
| isalpha() / isdigit() / isalnum() |
Non-empty character tests; not general number parsers.
|
Strings are immutable: methods return new strings. Assign the result if you need it. Some Unicode digit characters pass isdigit() but are not accepted by int().
SECTION 3 | LIST METHODS
| Item | Use and example |
|---|---|
| Create / read / update |
Lists are ordered mutable collections.
|
| append() |
Add one object to the end; returns None.
|
| extend() |
Add each item from an iterable.
|
| insert() |
Insert before an index.
|
| remove() |
Remove the first equal value; absent raises ValueError.
|
| pop() |
Remove and return an indexed item; default is last.
|
| index() / count() |
First matching index / number of matches.
|
| sort() |
Sort this list in place; returns None.
|
| sorted() |
Return a new sorted list; keep the source order.
|
| reverse() |
Reverse this list in place; does not sort it.
|
| copy() / slicing |
Create a shallow list copy.
|
| clear() / del |
Remove all items / delete a selected position.
|
Do not assign scores = scores.sort() or scores = scores.append(3): those methods return None. A shallow copy still shares nested mutable objects.
SECTION 3 | TUPLES AND SETS
| Item | Use and example |
|---|---|
| Tuple |
An immutable sequence; one item needs a comma.
|
| Tuple count() / index() |
Count occurrences / find the first index.
|
| Set / empty set |
Unique hashable values; no positional indexing.
|
| add() / update() |
Add one item / items from an iterable.
|
| discard() / remove() |
discard tolerates absence; remove raises KeyError.
|
| Union / intersection |
Combine values / keep common values.
|
| Difference / symmetric difference |
Only in a / in exactly one of the two sets.
|
Tuples can contain mutable objects. Set iteration order is not guaranteed. {} creates an empty dictionary, not an empty set.
SECTION 3 | DICTIONARY METHODS
| Item | Use and example |
|---|---|
| Create / read / update |
Map unique hashable keys to values.
|
| get() |
Read a value or a default without KeyError.
|
| keys() / values() / items() |
Views of keys, values or (key, value) pairs.
|
| Membership |
in tests keys, not values.
|
| update() |
Add keys and replace values for existing keys.
|
| pop() |
Remove and return a value; optional default.
|
| setdefault() |
Get a value, inserting a default if the key is absent.
|
| copy() / clear() |
Shallow copy / remove every item.
|
Dictionaries preserve insertion order. Reading a missing key with d[key] raises KeyError. Dictionary keys must be hashable.
SECTION 3 | NESTING AND COMPREHENSIONS
| Item | Use and example |
|---|---|
| Nested list |
Read a row, then an element in that row.
|
| List of dictionaries |
Keep related record fields together.
|
| List comprehension |
Build a new list from an expression.
|
| Filtered comprehension |
Keep only values meeting a condition.
|
| Dictionary / set comprehension |
Build mappings or unique values.
|
| Independent nested rows |
Avoid sharing one row object repeatedly.
|
[[0] * 3] * 2 repeats references to the same row. Use a comprehension when rows need to change independently.
SECTION 4 | FUNCTIONS AND PARAMETERS
| Item | Use and example |
|---|---|
| def / return |
Define a reusable job and return its result.
|
| Arguments |
Call using positional or keyword arguments.
|
| Return several values |
A comma-separated return packs a tuple.
|
| No explicit result |
Reaching the end returns None.
|
| Default collection |
Create a fresh list inside, not as a mutable default.
|
| *args / **kwargs |
Collect extra positional / keyword arguments.
|
| Lambda |
A short expression function, often a sorting key.
|
A return exits the current call. print() displays a value; it does not return that value to the caller.
SECTION 4 | SCOPE AND MODULES
| Item | Use and example |
|---|---|
| Local scope |
Parameters and assigned local names belong to a call.
|
| Avoid hidden state changes |
Prefer passing data and returning the new value.
|
| global |
Use only when a function must rebind a module name.
|
| import |
Use a module name to access its functions.
|
| from ... import ... |
Import a selected name. Avoid wildcard imports.
|
| Random values |
randint includes both ends; choice needs a non-empty sequence.
|
| Main entry point |
Run startup code when executed as a script.
|
Keep helper functions in clearly named modules and import them from another file. Do not name a script random.py or math.py if you intend to import the standard module.
SECTION 4 | SEARCHING, SORTING AND RECURSION
| Item | Use and example |
|---|---|
| Linear search |
Check each item; return a position or None.
|
| Binary search with bisect |
Sorted ascending input required; verify the match.
|
| Bubble sort pattern |
Sort in place through repeated adjacent comparisons.
|
| Recursion |
A base case plus progress towards it.
|
| Common growth rates |
Compare how work grows as input size n grows.
|
Prefer built-in sorting for ordinary applications. Recursive calls use stack space and Python limits recursion depth; never omit the base case.
SECTION 6 | CLASSES, OBJECTS AND METHODS
| Item | Use and example |
|---|---|
| Class / instance |
Define a type, then create an object.
|
| __init__ / self |
Initialise an instance; self refers to that instance.
|
| Instance vs class attribute |
Instance values differ; class attributes are shared defaults.
|
| Encapsulation convention |
A leading underscore signals an internal detail.
|
| Property |
Provide attribute-style access through a method.
|
| __str__ |
Return a readable string for print()/str().
|
Python does not enforce strict privacy through a single underscore. __init__ initialises an already-created instance. Put per-instance mutable lists in __init__, not in a shared class attribute.
SECTION 6 | INHERITANCE, POLYMORPHISM AND COMPOSITION
| Item | Use and example |
|---|---|
| Inheritance / override |
A subclass provides specialised behaviour.
|
| super() |
Call an inherited implementation.
|
| Polymorphism |
Use the same operation with different objects.
|
| Composition |
An object holds and uses another object.
|
Inheritance models an is-a relationship; composition models a has-a relationship. Polymorphism can also work without a shared explicit base class.
SECTION 6 | DATACLASSES AND DOCUMENTATION
| Item | Use and example |
|---|---|
| @dataclass |
Generate standard methods for a data-focused class.
|
| default_factory |
Give each dataclass instance its own mutable default.
|
| Type hints |
Document intended parameter and result types.
|
| Optional result |
A type union can include None. Python 3.10+.
|
| Docstring |
A first string inside a module, class or function.
|
Type hints are not automatic runtime validation. These examples target Python 3.10+; dataclasses generate methods but do not enforce annotated field types.
COMMON MIX-UPS
- input() returns text, even when the user types digits.
- = assigns; == compares; is tests identity.
- Indexes start at 0. Slice and range stop values are excluded.
- Initialise a running total before the loop, not on each pass.
- Strings are immutable; assign the result of a string method.
- Most list methods that only mutate the list return None.
- return gives a value to the caller; print() displays output.
- Two names can refer to one mutable object; copies may be shallow.
- Each instance needs its own mutable state, such as a member list.
- Type hints document types; they do not enforce them at runtime.
Official Python references: