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.

SECTION 1 | OUTPUT, VARIABLES AND TYPES

Output, variables and types reference
Item Use and example
print() Display one or more values.

name = "Alex"
print("Hello", name)
print("A", "B", sep=" | ")
Comments Explain a reason or assumption.

# Add a bonus for finishing the round.
score = 10 + 2
Assignment Bind a name to a value; = does not compare.

score = 10
score = score + 5
score += 2
Constants UPPER_CASE names signal intended constants.

POINTS_PER_WIN = 5
# Python does not enforce this naming convention.
int / float Whole-number / floating-point values.

lives = 3
price = 2.5
str / bool / None Text / logical value / absence of a value.

name = "Alex"
is_ready = True
result = None
type() / isinstance() Inspect a type / test type membership.

value = 12
print(type(value))
print(isinstance(value, int))
input() Read text from the user; returns str.

name = input("Your name: ")
print(f"Hello, {name}")
int() / float() / str() Convert values; unsuitable text raises ValueError.

count = int("12")
price = float("2.50")
label = str(count)
bool() Empty collections/strings, zero and None are falsy.

print(bool(""))      # False
print(bool("False")) # True: non-empty text
f-strings Insert expression values into text.

name = "Alex"
score = 12
print(f"{name} scored {score} points.")
Formatting numbers Format for display; the result is text.

price = 7.5
print(f"{price:.2f}") # 7.50

Use four spaces for each indentation level. Python names are case-sensitive. Input conversion alone is not full validation.

Back to topic links

SECTION 1 | ARITHMETIC AND NUMBERS

Arithmetic and numbers reference
Item Use and example
+ - * / Addition, subtraction, multiplication and division.

print(7 + 3) # 10
print(7 - 3) # 4
print(7 * 3) # 21
print(7 / 2) # 3.5
// Floor division: rounds down, not towards zero.

print(7 // 2)  # 3
print(-7 // 2) # -4
% Remainder; useful for even/odd checks.

print(7 % 2)  # 1
print(8 % 2)  # 0
** Exponentiation. Use parentheses for clear grouping.

print(2 ** 3)     # 8
print((2 + 3) * 4) # 20
+= -= *= /= Calculate from the current value and reassign.

total = 10
total += 5
total *= 2
print(total) # 30
abs() / round() Magnitude / numeric rounding.

print(abs(-8))      # 8
print(round(3.14159, 2)) # 3.14
min() / max() / sum() Smallest, largest and total in numeric data.

scores = [4, 7, 3]
print(min(scores)) # 3
print(max(scores)) # 7
print(sum(scores)) # 14
Average Check for an empty collection before dividing.

scores = [4, 7, 3]
if scores:
    average = sum(scores) / len(scores)
    print(average)

Floating-point arithmetic is approximate. round() uses ties-to-even for exact ties; binary representation can affect decimal-looking rounding cases.

Back to topic links

SECTION 2 | CONDITIONS AND BOOLEAN LOGIC

Conditions and boolean logic reference
Item Use and example
Comparison operators ==, !=, <, <=, > and >= compare values.

score = 10
print(score == 10) # True
print(score != 10) # False
and / or / not Combine conditions or reverse a truth value.

age = 14
has_permission = True
print(age >= 12 and has_permission)
print(not has_permission)
if / elif / else Run the first matching branch.

score = 75
if score >= 80:
    print("Gold")
elif score >= 50:
    print("Silver")
else:
    print("Bronze")
Chained comparisons A readable inclusive range check.

age = 14
print(12 <= age <= 18) # True
in / not in Test membership; dictionary membership tests keys.

name = "Alex"
print("x" in name)
print(3 not in [1, 2])
is None Test absence with identity, not a string.

result = None
if result is None:
    print("No result")
Conditional expression Choose one of two expression values.

score = 8
message = "Pass" if score >= 5 else "Retry"
print(message)

Use == for value equality. Use is for identity checks such as is None. and/or return operand values, not always bool values.

Back to topic links

SECTION 2 | LOOPS AND LOOP CONTROL

Loops and loop control reference
Item Use and example
for Repeat for each item in an iterable.

for name in ["Alex", "Sam"]:
    print(name)
range(stop) Integers starting at 0; stop is excluded.

for index in range(3):
    print(index) # 0, 1, 2
range(start, stop, step) Choose the start and step; stop stays excluded.

for number in range(2, 7, 2):
    print(number) # 2, 4, 6
for number in range(3, 0, -1):
    print(number) # 3, 2, 1
while Check a condition before each pass.

count = 3
while count > 0:
    print(count)
    count -= 1
break Exit the nearest loop immediately.

for number in range(1, 6):
    if number == 3:
        break
    print(number) # 1, 2
continue Skip the rest of this pass.

for number in range(1, 5):
    if number == 2:
        continue
    print(number) # 1, 3, 4
enumerate() Get an index/count and a value together.

names = ["Alex", "Sam"]
for position, name in enumerate(names, start=1):
    print(position, name)
zip() Pair iterables; normally stops at the shortest.

names = ["Alex", "Sam"]
scores = [8, 6]
for name, score in zip(names, scores):
    print(name, score)
Totalling / counting Initialise once outside the loop body.

total = 0
count = 0
for score in [4, 7, 3]:
    total += score
    count += 1
print(total, count) # 14, 3

The loop body is its indented repeated code. A while loop needs a route to a false condition or break; avoid accidental infinite loops.

Back to topic links

SECTION 2 | TRACING AND DEBUGGING

Tracing and debugging reference
Item Use and example
Labelled output Inspect values at the step being investigated.

total = 4
score = 7
print(f"Before: {total=}, {score=}")
total += score
print(f"After: {total=}")
breakpoint() Pause in a configured debugger; usually pdb by default.

score = 12
# Uncomment when deliberately debugging:
# breakpoint()
print(score)
Syntax / runtime / logic Parse failure / operation failure / wrong result.

# Syntax: missing colon after if
# Runtime: reading an invalid list index
# Logic: total = score instead of total += score
Boundary tests Check just below, on and above a threshold.

for score in [9, 10, 11]:
    print(score, score >= 10)

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

Back to topic links

SECTION 3 | STRINGS AND SLICING

Strings and slicing reference
Item Use and example
Indexing First character is index 0; -1 is the last.

text = "Python"
print(text[0])  # P
print(text[-1]) # n
Slicing start included, stop excluded; step is optional.

text = "Python"
print(text[1:4]) # yth
print(text[:3])  # Pyt
print(text[::2]) # Pto
print(text[::-1]) # nohtyP
len() Count string code points, not displayed glyphs.

print(len("Python")) # 6
lower() / upper() Return case-converted strings.

text = "Hello"
print(text.lower()) # hello
print(text.upper()) # HELLO
strip() Remove surrounding whitespace by default.

name = "  Alex  ".strip()
print(name) # Alex
replace() Return a string with occurrences replaced.

text = "red red blue"
print(text.replace("red", "green", 1))
split() Return a list split by whitespace or a separator.

print("Alex Sam".split())
print("red,blue".split(","))
join() Join an iterable of strings with a separator.

names = ["Alex", "Sam"]
print(", ".join(names)) # Alex, Sam
find() / index() First match: find returns -1 if absent; index raises.

text = "Python"
print(text.find("th")) # 2
print(text.find("z"))  # -1
print(text.index("th")) # 2
count() Count non-overlapping occurrences.

print("banana".count("an")) # 2
startswith() / endswith() Test a prefix or suffix.

filename = "notes.txt"
print(filename.startswith("notes"))
print(filename.endswith(".txt"))
isalpha() / isdigit() / isalnum() Non-empty character tests; not general number parsers.

print("Alex".isalpha()) # True
print("12".isdigit())   # True
print("-12".isdigit())  # False
print("A12".isalnum())  # True

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().

Back to topic links

SECTION 3 | LIST METHODS

List methods reference
Item Use and example
Create / read / update Lists are ordered mutable collections.

scores = [4, 7, 3]
print(scores[0])
scores[1] = 9
append() Add one object to the end; returns None.

scores = [4, 7]
scores.append(3)
print(scores) # [4, 7, 3]
extend() Add each item from an iterable.

scores = [4]
scores.extend([7, 3])
print(scores) # [4, 7, 3]
insert() Insert before an index.

names = ["Alex", "Sam"]
names.insert(1, "Jo")
print(names)
remove() Remove the first equal value; absent raises ValueError.

scores = [4, 7, 4]
scores.remove(4)
print(scores) # [7, 4]
pop() Remove and return an indexed item; default is last.

scores = [4, 7, 3]
last = scores.pop()
print(last) # 3
print(scores) # [4, 7]
index() / count() First matching index / number of matches.

scores = [4, 7, 4]
print(scores.index(7)) # 1
print(scores.count(4)) # 2
sort() Sort this list in place; returns None.

scores = [4, 7, 3]
scores.sort()
print(scores) # [3, 4, 7]
sorted() Return a new sorted list; keep the source order.

scores = [4, 7, 3]
ordered = sorted(scores, reverse=True)
print(ordered) # [7, 4, 3]
reverse() Reverse this list in place; does not sort it.

scores = [4, 7, 3]
scores.reverse()
print(scores) # [3, 7, 4]
copy() / slicing Create a shallow list copy.

original = [4, 7, 3]
copy = original.copy()
first_two = original[:2]
clear() / del Remove all items / delete a selected position.

scores = [4, 7, 3]
del scores[1]
scores.clear()

Do not assign scores = scores.sort() or scores = scores.append(3): those methods return None. A shallow copy still shares nested mutable objects.

Back to topic links

SECTION 3 | TUPLES AND SETS

Tuples and sets reference
Item Use and example
Tuple An immutable sequence; one item needs a comma.

point = (3, 5)
single = (3,)
x, y = point
print(x, y)
Tuple count() / index() Count occurrences / find the first index.

values = (2, 3, 2)
print(values.count(2)) # 2
print(values.index(3)) # 1
Set / empty set Unique hashable values; no positional indexing.

colours = {"red", "blue", "red"}
empty = set()
print(len(colours)) # 2
add() / update() Add one item / items from an iterable.

tags = {"python"}
tags.add("robotics")
tags.update(["web", "sql"])
discard() / remove() discard tolerates absence; remove raises KeyError.

tags = {"python", "web"}
tags.discard("missing")
tags.remove("web")
Union / intersection Combine values / keep common values.

a = {1, 2}
b = {2, 3}
print(a | b) # {1, 2, 3}, order not guaranteed
print(a & b) # {2}
Difference / symmetric difference Only in a / in exactly one of the two sets.

a = {1, 2}
b = {2, 3}
print(a - b) # {1}
print(a ^ b) # {1, 3}, order not guaranteed

Tuples can contain mutable objects. Set iteration order is not guaranteed. {} creates an empty dictionary, not an empty set.

Back to topic links

SECTION 3 | DICTIONARY METHODS

Dictionary methods reference
Item Use and example
Create / read / update Map unique hashable keys to values.

student = {"name": "Alex", "score": 8}
print(student["name"])
student["score"] = 10
get() Read a value or a default without KeyError.

student = {"name": "Alex"}
print(student.get("score", 0)) # 0
keys() / values() / items() Views of keys, values or (key, value) pairs.

student = {"name": "Alex", "score": 8}
for key, value in student.items():
    print(key, value)
Membership in tests keys, not values.

student = {"name": "Alex"}
print("name" in student) # True
print("Alex" in student) # False
update() Add keys and replace values for existing keys.

student = {"name": "Alex", "score": 8}
student.update({"score": 10, "year": 12})
pop() Remove and return a value; optional default.

student = {"name": "Alex", "score": 8}
score = student.pop("score", 0)
print(score) # 8
setdefault() Get a value, inserting a default if the key is absent.

counts = {}
counts.setdefault("wins", 0)
counts["wins"] += 1
copy() / clear() Shallow copy / remove every item.

student = {"name": "Alex"}
copy = student.copy()
copy.clear()

Dictionaries preserve insertion order. Reading a missing key with d[key] raises KeyError. Dictionary keys must be hashable.

Back to topic links

SECTION 3 | NESTING AND COMPREHENSIONS

Nesting and comprehensions reference
Item Use and example
Nested list Read a row, then an element in that row.

grid = [[1, 2], [3, 4]]
print(grid[1][0]) # 3
List of dictionaries Keep related record fields together.

students = [{"name": "Alex", "score": 8}]
print(students[0]["score"]) # 8
List comprehension Build a new list from an expression.

squares = [n * n for n in range(4)]
print(squares) # [0, 1, 4, 9]
Filtered comprehension Keep only values meeting a condition.

even = [n for n in range(6) if n % 2 == 0]
print(even) # [0, 2, 4]
Dictionary / set comprehension Build mappings or unique values.

squares = {n: n * n for n in range(3)}
lengths = {len(word) for word in ["cat", "dog", "bird"]}
Independent nested rows Avoid sharing one row object repeatedly.

grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 9
print(grid) # [[9, 0, 0], [0, 0, 0]]

[[0] * 3] * 2 repeats references to the same row. Use a comprehension when rows need to change independently.

Back to topic links

SECTION 4 | FUNCTIONS AND PARAMETERS

Functions and parameters reference
Item Use and example
def / return Define a reusable job and return its result.

def area(width, height):
    return width * height

print(area(4, 3)) # 12
Arguments Call using positional or keyword arguments.

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}"

print(greet("Alex"))
print(greet(name="Sam", greeting="Hi"))
Return several values A comma-separated return packs a tuple.

def bounds(values):
    return min(values), max(values)

low, high = bounds([4, 7, 3])
No explicit result Reaching the end returns None.

def show(name):
    print(name)

result = show("Alex")
print(result) # None
Default collection Create a fresh list inside, not as a mutable default.

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item("pen"))
*args / **kwargs Collect extra positional / keyword arguments.

def total(*scores):
    return sum(scores)

def profile(**details):
    return details

print(total(4, 7, 3))
print(profile(name="Alex"))
Lambda A short expression function, often a sorting key.

students = [{"name": "Alex", "score": 8}]
ordered = sorted(students, key=lambda s: s["score"])

A return exits the current call. print() displays a value; it does not return that value to the caller.

Back to topic links

SECTION 4 | SCOPE AND MODULES

Scope and modules reference
Item Use and example
Local scope Parameters and assigned local names belong to a call.

def double(number):
    result = number * 2
    return result

answer = double(4)
# result is not available as a local name here.
Avoid hidden state changes Prefer passing data and returning the new value.

def add_bonus(score, bonus):
    return score + bonus

score = add_bonus(10, 2)
global Use only when a function must rebind a module name.

count = 0
def increment():
    global count
    count += 1

increment()
import Use a module name to access its functions.

import math

print(math.sqrt(81)) # 9.0
from ... import ... Import a selected name. Avoid wildcard imports.

from math import sqrt

print(sqrt(81)) # 9.0
Random values randint includes both ends; choice needs a non-empty sequence.

import random

roll = random.randint(1, 6)
name = random.choice(["Alex", "Sam"])
Main entry point Run startup code when executed as a script.

def main():
    print("Ready")

if __name__ == "__main__":
    main()

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.

Back to topic links

SECTION 4 | SEARCHING, SORTING AND RECURSION

Searching, sorting and recursion reference
Item Use and example
Linear search Check each item; return a position or None.

def linear_search(values, target):
    for index, value in enumerate(values):
        if value == target:
            return index
    return None

print(linear_search([4, 7, 3], 7)) # 1
Binary search with bisect Sorted ascending input required; verify the match.

from bisect import bisect_left

values = [3, 4, 7]
position = bisect_left(values, 4)
found = position < len(values) and values[position] == 4
print(found) # True
Bubble sort pattern Sort in place through repeated adjacent comparisons.

values = [4, 7, 3]
for end in range(len(values) - 1, 0, -1):
    for index in range(end):
        if values[index] > values[index + 1]:
            values[index], values[index + 1] = (
                values[index + 1], values[index]
            )
print(values) # [3, 4, 7]
Recursion A base case plus progress towards it.

def factorial(number):
    # Assume a non-negative integer.
    if number == 0:
        return 1
    return number * factorial(number - 1)

print(factorial(4)) # 24
Common growth rates Compare how work grows as input size n grows.

# Linear scan: O(n)
# Binary search in a sorted list: O(log n)
# Basic bubble sort: O(n ** 2)
# Built-in list sorting: O(n log n) worst case

Prefer built-in sorting for ordinary applications. Recursive calls use stack space and Python limits recursion depth; never omit the base case.

Back to topic links

SECTION 6 | CLASSES, OBJECTS AND METHODS

Classes, objects and methods reference
Item Use and example
Class / instance Define a type, then create an object.

class Student:
    def __init__(self, name):
        self.name = name

student = Student("Alex")
print(student.name)
__init__ / self Initialise an instance; self refers to that instance.

class Counter:
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1

counter = Counter()
counter.increment()
print(counter.value) # 1
Instance vs class attribute Instance values differ; class attributes are shared defaults.

class Student:
    school = "Coding Club"

    def __init__(self, name):
        self.name = name

alex = Student("Alex")
sam = Student("Sam")
Encapsulation convention A leading underscore signals an internal detail.

class Counter:
    def __init__(self):
        self._value = 0

    def read(self):
        return self._value
Property Provide attribute-style access through a method.

class Square:
    def __init__(self, side):
        self.side = side

    @property
    def area(self):
        return self.side ** 2

print(Square(4).area) # 16
__str__ Return a readable string for print()/str().

class Student:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

print(Student("Alex"))

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.

Back to topic links

SECTION 6 | INHERITANCE, POLYMORPHISM AND COMPOSITION

Inheritance, polymorphism and composition reference
Item Use and example
Inheritance / override A subclass provides specialised behaviour.

class Animal:
    def speak(self):
        return "Sound"

class Dog(Animal):
    def speak(self):
        return "Woof"

print(Dog().speak())
super() Call an inherited implementation.

class Person:
    def __init__(self, name):
        self.name = name

class Student(Person):
    def __init__(self, name, year):
        super().__init__(name)
        self.year = year

student = Student("Alex", 12)
Polymorphism Use the same operation with different objects.

class Dog:
    def speak(self):
        return "Woof"

class Cat:
    def speak(self):
        return "Meow"

for animal in [Dog(), Cat()]:
    print(animal.speak())
Composition An object holds and uses another object.

class Engine:
    def start(self):
        return "Running"

class Robot:
    def __init__(self):
        self.engine = Engine()

robot = Robot()
print(robot.engine.start())

Inheritance models an is-a relationship; composition models a has-a relationship. Polymorphism can also work without a shared explicit base class.

Back to topic links

SECTION 6 | DATACLASSES AND DOCUMENTATION

Dataclasses and documentation reference
Item Use and example
@dataclass Generate standard methods for a data-focused class.

from dataclasses import dataclass

@dataclass
class Student:
    name: str
    score: int = 0

student = Student("Alex", 8)
print(student.score)
default_factory Give each dataclass instance its own mutable default.

from dataclasses import dataclass, field

@dataclass
class Team:
    members: list[str] = field(default_factory=list)

team = Team()
team.members.append("Alex")
Type hints Document intended parameter and result types.

def greet(name: str) -> str:
    return f"Hello, {name}"

names: list[str] = ["Alex", "Sam"]
Optional result A type union can include None. Python 3.10+.

def first(values: list[int]) -> int | None:
    return values[0] if values else None

print(first([])) # None
Docstring A first string inside a module, class or function.

def area(width: float, height: float) -> float:
    """Return the area for the supplied dimensions."""
    return width * height

print(area.__doc__)

Type hints are not automatic runtime validation. These examples target Python 3.10+; dataclasses generate methods but do not enforce annotated field types.

Back to topic links

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.

BACK TO PYTHON

Official Python references: