Python cheat sheet

The most-used syntax —variables, collections, loops, functions, classes, files— in tables for quick reference.

Quick reference. To learn each topic in depth, go to the interactive Python examples.

Types and variables

nombre = "Ana"          # str
edad = 30               # int
altura = 1.75           # float
activo = True           # bool
nada = None             # ausencia de valor

f"{nombre} tiene {edad}"          # f-string
int("42"); str(42); float("1.5")  # conversiones
type(edad)                        # <class 'int'>

Collections

Control flow

if edad >= 18:
    print("mayor")
elif edad >= 13:
    print("adolescente")
else:
    print("menor")

for i in range(5):          # 0, 1, 2, 3, 4
    print(i)

for x in lista:
    if x < 0: continue
    if x > 100: break

while queda_trabajo:
    trabajar()

match comando:               # Python 3.10+
    case "salir": ...
    case _: ...

Functions and comprehensions

def saluda(nombre, saludo="Hola"):
    return f"{saludo}, {nombre}"

def suma(*args):        # nº variable de argumentos
    return sum(args)

cuadrados = [x*x for x in range(10)]
pares = [x for x in nums if x % 2 == 0]
por_nombre = {u.id: u.nombre for u in usuarios}

doble = lambda x: x * 2
list(map(str, nums)); list(filter(None, nums))

Classes

class Perro:
    def __init__(self, nombre):
        self.nombre = nombre

    def ladra(self):
        return f"{self.nombre}: guau"

    def __str__(self):
        return f"Perro({self.nombre})"

p = Perro("Toby")
p.ladra()

Files and errors

with open("datos.txt", encoding="utf-8") as f:
    texto = f.read()
    # for linea in f: ...

with open("salida.txt", "w", encoding="utf-8") as f:
    f.write("hola\n")

try:
    n = int(entrada)
except ValueError:
    print("no es un número")
finally:
    print("siempre se ejecuta")

Other cheat sheets

Java · JavaScript · SQL · Git