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
| Tipo | Crear | Operaciones frecuentes |
|---|---|---|
| lista | xs = [1, 2, 3] | xs.append(4) · xs[0] · xs[-1] · xs[1:3] · len(xs) · xs.sort() |
| tupla | p = (1, 2) | inmutable · x, y = p |
| dict | d = {"a": 1} | d["a"] · d.get("b", 0) · d.items() · "a" in d |
| set | s = {1, 2, 3} | s.add(4) · x in s · a & b · a | b |
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