Skip to content
Codewilds

Python cheat sheet

The essential Python syntax on one page. Every snippet comes from a lesson of our interactive Learn Python course — click "Practise" to write it yourself and get instant feedback.

Last updated on .

Fundamentals

Python Hello World: Your First Program

Write your first Python program with print(), learn how Python runs code line by line and add comments. It all runs in your browser — no install.

print("Hello, World!")
Practise: Python Hello World: Your First Program

Python Variables and Data Types

Learn Python variables and the core data types — int, float, str, bool and None — plus type() and type conversion, with an interactive exercise.

hero = "Ada"
level = 3
print(hero, "is level", level)  # Ada is level 3
Practise: Python Variables and Data Types

Python Numbers and Arithmetic Operators

Master Python arithmetic: + - * /, floor division //, modulo %, exponent **, operator precedence and float gotchas. Practise with real code.

gold = 250          # int
price = 4.99        # float
huge = 2 ** 100     # ints can be as large as you like
budget = 1_000_000  # underscores make long numbers readable
Practise: Python Numbers and Arithmetic Operators

Python Strings and f-Strings

Work with Python strings: indexing, slicing, string methods like strip(), upper() and replace(), and formatting values with f-strings. Interactive lesson.

spell = "Fireball"
quote = 'Speak, friend, and enter.'
scroll = """Line one
Line two"""
Practise: Python Strings and f-Strings

Python If, Elif and Else Statements

Make decisions in Python with if, elif and else, comparison and logical operators (and, or, not) and truthy values. Write and test real code.

health = 25

if health < 30:
    print("Warning: low health!")
print("Turn over.")
Practise: Python If, Elif and Else Statements

Python Loops: for, range() and while

Repeat work with Python for loops, range(), while loops, break and continue. Learn the accumulator pattern and how to avoid infinite loops.

for letter in "hiss":
    print(letter)
Practise: Python Loops: for, range() and while

Functions

Python Functions: def, Parameters and return

Define your own Python functions with def, pass parameters, return values instead of printing them, and document them with docstrings and type hints.

def greet(name):
    return f"Welcome to Serpent Hollow, {name}!"


message = greet("Ada")
print(message)  # Welcome to Serpent Hollow, Ada!
Practise: Python Functions: def, Parameters and return

Python Function Arguments: Defaults, *args and **kwargs

Learn Python default parameter values, keyword arguments, *args and **kwargs, keyword-only parameters and the mutable default argument trap.

def describe(name, job):
    return f"{name} the {job}"


print(describe("Ada", "engineer"))          # Ada the engineer
print(describe(job="wizard", name="Merl"))  # Merl the wizard
Practise: Python Function Arguments: Defaults, *args and **kwargs

Python Scope, Closures and Lambda Functions

Understand Python variable scope (LEGB), global and nonlocal, closures and anonymous lambda functions — then pass functions around like any other value.

realm = "Serpent Hollow"   # global


def welcome():
    visitor = "Ada"         # local
    return f"{visitor} enters {realm}"


print(welcome())   # Ada enters Serpent Hollow
print(visitor)     # NameError: name 'visitor' is not defined
Practise: Python Scope, Closures and Lambda Functions

Lists & Tuples

Python Lists: Indexing and Slicing

Learn Python lists: create them, read items by index, use negative indexes and slice with [start:stop:step] to copy, reverse and rotate sequences.

heroes = ["Ada", "Bo", "Cy"]
scores = [98, 75, 88]
mixed = ["potion", 3, True, None]
empty = []

print(len(heroes))          # 3
print(list(range(5)))       # [0, 1, 2, 3, 4]
print(list("hiss"))         # ['h', 'i', 's', 's']
Practise: Python Lists: Indexing and Slicing

Python List Methods and Sorting

Use Python list methods — append, extend, insert, remove, pop — and sort lists with sort() vs sorted(), reverse=True and key functions.

bag = ["rope"]
bag.append("torch")             # add one item to the end
bag.extend(["map", "potion"])   # add every item from another iterable
bag.insert(0, "sword")          # insert at a position
print(bag)  # ['sword', 'rope', 'torch', 'map', 'potion']
Practise: Python List Methods and Sorting

Python Tuples and Unpacking

Learn Python tuples — immutable sequences for records and multiple return values — plus tuple unpacking, star unpacking and swapping variables.

point = (3, 4)
color = (255, 128, 0)
hero = ("Ada", 98)
single = (5,)        # one-item tuple: the comma is required!
not_a_tuple = (5)    # just the number 5 in parentheses
empty = ()
Practise: Python Tuples and Unpacking

Python List Comprehensions

Write Python list comprehensions to map, filter and flatten lists in one readable line — with if filters, conditional expressions and nested loops.

numbers = [1, 2, 3, 4]
doubled = []
for n in numbers:
    doubled.append(n * 2)
Practise: Python List Comprehensions

Dictionaries & Sets

Python Dictionaries: Keys, Values and Methods

Learn Python dictionaries: create, read and update key-value pairs, use get(), items() and setdefault(), loop over dicts and count things.

hero = {"name": "Ada", "level": 3, "class": "wizard"}
prices = {"potion": 5, "rope": 2}
empty = {}

print(hero["name"])    # Ada
print(len(hero))       # 3
print(hero["mana"])    # KeyError: 'mana'
Practise: Python Dictionaries: Keys, Values and Methods

Python Sets and Set Operations

Use Python sets to remove duplicates, test membership fast and combine data with union, intersection and difference. Interactive exercises.

elements = {"fire", "ice", "storm"}
rolls = set([3, 6, 3, 1, 6])
print(rolls)            # {1, 3, 6}
print(set("hollow"))    # {'h', 'o', 'l', 'w'}  (order may vary)
empty = set()           # NOT {} — that's an empty dict!
Practise: Python Sets and Set Operations

Python Dictionary and Set Comprehensions

Build Python dictionaries and sets in one line with dict and set comprehensions: transform, filter and invert data the Pythonic way.

squares = {n: n * n for n in range(1, 5)}
print(squares)   # {1: 1, 2: 4, 3: 9, 4: 16}

heroes = ["Ada", "Bo", "Cyrus"]
name_lengths = {name: len(name) for name in heroes}
print(name_lengths)   # {'Ada': 3, 'Bo': 2, 'Cyrus': 5}
Practise: Python Dictionary and Set Comprehensions

Classes & OOP

Python Classes and Objects: __init__, Methods and Attributes

Learn object-oriented Python: define classes, initialise objects with __init__ and self, write methods, and use instance vs class attributes.

class Potion:
    def __init__(self, name, power):
        self.name = name
        self.power = power


healing = Potion("Healing", 25)
mana = Potion("Mana", 40)
print(healing.name, healing.power)   # Healing 25
print(mana.power)                    # 40
Practise: Python Classes and Objects: __init__, Methods and Attributes

Python Inheritance and super()

Reuse code with Python inheritance: create subclasses, override methods, extend parent classes with super() and check types with isinstance().

class Enemy:
    def __init__(self, name, health):
        self.name = name
        self.health = health

    def describe(self):
        return f"{self.name} ({self.health} HP)"

    def attack(self):
        return 3


class Goblin(Enemy):
    pass


grub = Goblin("Grub", 30)
print(grub.describe())   # Grub (30 HP)
print(grub.attack())     # 3
Practise: Python Inheritance and super()

Python Dunder Methods: __str__, __repr__ and __eq__

Make Python classes feel built-in with dunder (magic) methods: __str__ and __repr__ for printing, __eq__ for equality and __add__ for operators.

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y


v = Vector(1, 2)
print(v)                          # <__main__.Vector object at 0x7f3a...>
print(Vector(1, 2) == Vector(1, 2))   # False — two different objects
Practise: Python Dunder Methods: __str__, __repr__ and __eq__

Python Dataclasses

Cut boilerplate with Python dataclasses: auto-generated __init__, __repr__ and __eq__, default values, default_factory, frozen and ordered classes.

from dataclasses import dataclass


@dataclass
class Point:
    x: int
    y: int


p = Point(3, 4)
print(p)                    # Point(x=3, y=4)
print(p.x)                  # 3
print(p == Point(3, 4))     # True
Practise: Python Dataclasses

Errors & Pythonic Tools

Raising Custom Exceptions in Python

Raise exceptions in Python with raise, design custom exception classes that carry extra data, re-raise errors and chain them with raise ... from.

def set_volume(level):
    if not 0 <= level <= 10:
        raise ValueError(f"Volume must be between 0 and 10, got {level}")
    return level


set_volume(11)   # ValueError: Volume must be between 0 and 10, got 11
Practise: Raising Custom Exceptions in Python

Python Iterators and Generators

Understand Python iterators, iter() and next(), and write lazy generators with yield and generator expressions to process data efficiently.

letters = iter(["a", "b"])
print(next(letters))          # a
print(next(letters))          # b
print(next(letters, "done"))  # done  (a default instead of StopIteration)
Practise: Python Iterators and Generators

Python enumerate(), zip() and sorted() with key

Write Pythonic loops with enumerate() and zip(), and sort anything with sorted(key=...), lambda functions and multi-key tuples. Interactive lesson.

heroes = ["Ada", "Bo", "Cy"]

for index, hero in enumerate(heroes):
    print(index, hero)          # 0 Ada / 1 Bo / 2 Cy

for rank, hero in enumerate(heroes, start=1):
    print(f"{rank}. {hero}")    # 1. Ada / 2. Bo / 3. Cy
Practise: Python enumerate(), zip() and sorted() with key