This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · Esta página necesita un navegador reciente (con soporte para SharedArrayBuffer). Por favor, actualiza Chrome, Edge, Firefox o Safari a la última versión.
1Getting started · Introducción
1.1
Tu primer programa
English
Python runs your code one line at a time. Each line is a statement 语句. A program 程序 is just a list of statements that run from top to bottom.
The print() function shows text on the screen. This is called output 输出. Text inside quotes is a string 字符串.
Each print() starts a new line.
Quotes can be "double" or 'single' — both make a string.
A program does nothing until you run it.
Español
Python ejecuta tu código línea por línea. Cada línea es una declaración 语句. Un programa 程序 es simplemente una lista de declaraciones que se ejecutan de arriba hacia abajo.
La función print() muestra texto en la pantalla. Esto se denomina salida 输出. El texto entre comillas es una cadena 字符串.
print("Hello, world!")
print("I am learning Python")
Cada print() inicia una nueva línea.
Las comillas pueden ser "double" o 'single' — ambas crean una cadena.
Un programa no hace nada hasta que lo ejecutas.
El código fuente pasa por el intérprete para producir salida
1.2
Comentarios y estilo del código
English
A comment 注释 starts with #. Python ignores everything after the # on that line. Comments explain your code to people; they do not change what the code does.
Good style makes code easy to read:
Use clear names that say what a value means.
Put one statement on each line.
Do not add spaces at the start of a normal line. In Python, spacing at the start (indentation 缩进) has a special meaning, so a wrong space gives an error 错误.
Español
Un comentario 注释 comienza con #. Python ignora todo lo que hay después del # en esa línea. Los comentarios explican tu código a las personas; no cambian lo que hace el código.
# This line is a note for humans
print("Hi") # you can also comment at the end of a line
Un buen estilo hace que el código sea fácil de leer:
Usa nombres claros que indiquen qué significa un valor.
Coloca una declaración por línea.
No agregues espacios al inicio de una línea normal. En Python, los espacios al principio (indentación 缩进) tienen un significado especial, por lo que un espacio incorrecto provoca un error 错误.
1.3
Entrada, proceso, salida
English
Many programs follow a simple plan: input 输入 → process → output. You get some data, do something with it, then show a result.
The input() function reads text that the user types. It always gives back a string.
input() waits for the user to type and press Enter.
Store the typed text in a variable 变量 so you can use it later.
Because input() returns a string, change it with int(...) first if you need a number.
Common mistakes
Forgetting the quotes: print(Hello) looks for a variable named Hello and raises a NameError. Text needs quotes: print("Hello").
A stray space at the start of a line: Python reads indentation as structure, so it raises an IndentationError.
Assuming input() returns a number. It always returns a string, so wrap it in int(...) before doing any maths.
Español
Muchos programas siguen un plan simple: entrada 输入 → proceso → salida. Obtienes datos, haces algo con ellos y luego muestras un resultado.
La función input() lee el texto que el usuario escribe. Siempre devuelve una cadena.
name = input("What is your name? ")
print("Hello, " + name)
input() espera a que el usuario escriba y presione Enter.
Almacena el texto escrito en una variable 变量 para poder usarlo más tarde.
Dado que input() devuelve una cadena, conviértela con int(...) primero si necesitas un número.
Errores comunes
Olvidar las comillas: print(Hello) busca una variable llamada Hello y genera un NameError. El texto necesita comillas: print("Hello").
Un espacio suelto al inicio de una línea: Python interpreta la indentación como estructura, por lo que genera un IndentationError.
Asumir que input() devuelve un número. Siempre devuelve una cadena, así que envuélvela en int(...) antes de hacer cualquier cálculo matemático.
2Variables, types & operators · Variables, tipos y operadores
2.1
Variables y asignación
English
A variable 变量 is a name for a value 值. You make one with =, which is called assignment 赋值. The name goes on the left; the value goes on the right.
Now age holds 17. Use the name anywhere you need the value, and change it later:
The = sign does not mean "equal". It means "store the right side under the left name".
To test if two values are equal, use == (see below).
Español
Una variable es un nombre para un valor. Se crea con =, que se llama asignación. El nombre va a la izquierda; el valor va a la derecha.
age = 17
name = "Mei"
price = 9.99
print(age, name, price)
Ahora age contiene 17. Usa el nombre donde necesites el valor, y cámbialo más adelante:
age = 17
age = age + 1 # age is now 18
print(age)
Cada nombre de variable apunta a un valor en la memoria
El signo = no significa "igual". Significa "almacenar el lado derecho bajo el nombre del lado izquierdo".
Para probar si dos valores son iguales, usa == (ver abajo).
2.2
Números: int y float
English
Python has two main number types. An integer 整数 (int) is a whole number like 17. A float 浮点数 (float) has a decimal point like 9.99.
These operators 运算符 work on numbers:
Operator
Meaning
Example
Result
+
add
3 + 2
5
-
subtract
3 - 2
1
*
multiply
3 * 2
6
/
divide (always float)
7 / 2
3.5
//
integer divide
7 // 2
3
%
remainder (modulo)
7 % 2
1
**
power
2 ** 3
8
/ always gives a float, so 4 / 2 is 2.0.
// and % go together: 17 // 5 is 3, and 17 % 5 is 2.
Español
Python tiene dos tipos principales de números. Un entero (int) es un número completo como 17. Un punto flotante (float) tiene un punto decimal como 9.99.
Estos operadores funcionan sobre números:
Operador
Significado
Ejemplo
Resultado
+
sumar
3 + 2
5
-
restar
3 - 2
1
*
multiplicar
3 * 2
6
/
dividir (siempre float)
7 / 2
3.5
//
división entera
7 // 2
3
%
residuo (módulo)
7 % 2
1
**
potencia
2 ** 3
8
/ siempre da un float, así que 4 / 2 es 2.0.
// y % van juntos: 17 // 5 es 3, y 17 % 5 es 2.
2.3
Expresiones y conversión de tipo
English
An expression 表达式 is anything that has a value, like 3 + 4 * 2. Python uses normal maths order (* and / before + and -); add brackets to make the order clear.
input() gives a string, so convert it before doing maths. Changing a value from one type to another is type conversion 类型转换:
int("abc") fails, so only convert text that looks like a number.
Mixing types fails too: "age: " + 17 is an error; write "age: " + str(17).
Español
Una expresión es cualquier cosa que tenga un valor, como 3 + 4 * 2. Python usa el orden matemático normal (* y / antes que + y -); añade paréntesis para que el orden sea claro.
input() devuelve una cadena, así que conviértela antes de hacer matemáticas. Cambiar un valor de un tipo a otro es conversión de tipo:
age = int("17") # text "17" -> number 17
price = float("9.99") # text -> 9.99
label = str(17) # number -> text "17"
print(age, price, label)
int("abc") falla, así que solo convierte textos que parezcan números.
Mezclar tipos también falla: "age: " + 17 es un error; escribe "age: " + str(17).
2.4
Booleanos y comparación
English
A Boolean 布尔值 is one of just two values: True or False. A comparison 比较 gives back a Boolean.
Operator
Meaning
==
equal to
!=
not equal to
<>
less than / greater than
<=>=
less / greater than or equal to
Join comparisons with and, or, not:
Common mistakes
/ always gives a float, even 4 / 2 is 2.0. Use // when you want a whole number.
Using = where you mean ==: = assigns a value, == tests whether two values are equal.
Joining a string and a number: "age: " + 5 raises a TypeError. Convert first with str(5).
Floats are not exact, so 0.1 + 0.2 is not exactly 0.3 — avoid == on float results.
Español
Un booleano es uno de solo dos valores: True o False. Una comparación devuelve un booleano.
Una comparación da un valor booleano — ya sea True o False.
if / elif / else: solo se ejecuta una rama
4.2
Combinar condiciones
English
Join conditions with and, or, not. and needs both sides true; or needs either side true; not flips a Boolean.
Use brackets to make the order clear: (a or b) and c.
Common mistakes
Write elif, not else if.
Every if / elif / else line ends with a colon :, and its body must be indented.
if x = 5: is an error — use == to compare.
else takes no condition; only if and elif do.
Español
Une condiciones con and, or, not. and requiere que ambos lados sean verdaderos; or requiere que al menos uno de los lados sea verdadero; not invierte un booleano.
age = 16
has_ticket = True
if age >= 18 and has_ticket:
print("entry allowed")
else:
print("entry refused")
# entry refused
Usa paréntesis para dejar claro el orden: (a or b) and c.
temp = 30
if temp > 25 and not temp > 35:
print("warm but ok")
# warm but ok
Errores comunes
Escribe elif, no else if.
Cada línea if / elif / else termina con dos puntos :, y su cuerpo debe tener sangría.
if x = 5: es un error — usa == para comparar.
else no recibe ninguna condición; solo if y elif lo hacen.
5Iteration · Iteración
5.1
bucles for y range
English
A loop 循环 repeats code. A for loop repeats once for each item in a sequence 序列. range(n) gives the numbers 0 up to n - 1.
range(a, b) goes from a up to (but not including) b.
range(a, b, step) adds a step 步长 each time.
Español
Un bucle repite código. Un for bucle se repite una vez por cada elemento en una secuencia. range(n) genera los números 0 hasta n - 1.
for i in range(5):
print(i)
# 0, then 1, 2, 3, 4 (each on its own line)
range(a, b) va desde a hasta (sin incluir) b.
range(a, b, step) añade un paso cada vez.
for n in range(2, 11, 2):
print(n) # 2 4 6 8 10
for i in range(n): el cuerpo se ejecuta con i = 0 … n-1
5.2
El patrón acumulador
English
To build a result across a loop, start a variable before the loop, then update 更新 it each turn. This is the accumulator 累加器 pattern.
The same idea counts how many items match a test.
Español
Para construir un resultado a través de un bucle, inicia una variable antes del bucle, luego actualízala en cada vuelta. Este es el patrón acumulador.
total = 0
for n in range(1, 6):
total = total + n
print(total) # 15
La misma idea cuenta cuántos elementos coinciden con una prueba.
count = 0
for letter in "banana":
if letter == "a":
count = count + 1
print(count) # 3
5.3
Bucle while
English
A while loop repeats as long as a condition stays true. Change something inside, or it never stops — an infinite loop 无限循环.
break leaves the loop straight away.
Español
Un while bucle se repite mientras una condición permanezca verdadera. Cambia algo dentro, o nunca terminará —un bucle infinito.
n = 1
while n <= 3:
print(n)
n = n + 1
# 1 2 3
break sale del bucle inmediatamente.
total = 0
while True:
total = total + 10
if total >= 30:
break
print(total) # 30
5.4
Buces anidados
English
A loop inside another loop is a nested loop 嵌套循环. The inner loop 内层循环 runs fully for each turn of the outer loop 外层循环.
Common mistakes
range(n) goes from 0 to n - 1, not 1 to n — the classic off-by-one error.
Changing a list while looping over it skips items; loop over a copy if you must remove things.
Forgetting to change the loop variable in a while makes it run forever.
Indentation decides what is inside the loop; a wrongly-indented line runs only once, after the loop.
Español
Un bucle dentro de otro bucle es un bucle anidado. El bucle interno se ejecuta completamente por cada vuelta del bucle externo.
for row in range(3):
line = ""
for col in range(3):
line = line + "*"
print(line)
# ***
# ***
# ***
Errores comunes
range(n) va desde 0 hasta n - 1, no desde 1 hasta n —el clásico error off-by-one.
Modificar una lista mientras se itera sobre ella salta elementos; itera sobre una copia si debes eliminar cosas.
Olvidar cambiar la variable del bucle en un while hace que se ejecute para siempre.
La sangría decide qué está dentro del bucle; una línea mal sangrada se ejecuta solo una vez, después del bucle.
6Lists & 2-D lists · Listas y listas 2-D
6.1
Listas
English
A list 列表 holds many values in order, inside []. Each item 元素 has an index (from 0).
Change an item by its index: scores[1] = 100.
A list can grow and shrink; a string cannot.
The everyday list tools:
Tool
Does
a.append(x)
adds x at the end
a.insert(i, x)
inserts x at position i
a.remove(x)
removes the first x
a.pop() / a.pop(i)
removes and returns the last item / item i
a.sort()
sorts the list in place
sorted(a)
returns a NEW sorted list
x in a
is x in the list?
len(a), sum(a), max(a), min(a)
size and quick maths
Español
Una lista 列表 holds many values in order, inside []. Each item 元素 has an index (from 0).
scores = [88, 71, 95]
print(scores[0]) # 88
print(len(scores)) # 3
scores.append(60) # add to the end
print(scores) # [88, 71, 95, 60]
Change an item by its index: scores[1] = 100.
Una lista puede crecer y encogerse; una cadena de texto (string) no puede.
The everyday list tools:
Tool
Does
a.append(x)
adds x at the end
a.insert(i, x)
inserts x at position i
a.remove(x)
removes the first x
a.pop() / a.pop(i)
removes and returns the last item / item i
a.sort()
sorts the list in place
sorted(a)
returns a NEW sorted list
x in a
is x in the list?
len(a), sum(a), max(a), min(a)
size and quick maths
Los índices de las listas comienzan en 0
6.2
Recorrer una lista
English
To traverse 遍历 a list is to visit each item. A for loop does this with no index needed.
Use enumerate when you also need the index.
Español
Para traversing 遍历 a list es visitar cada elemento. Un bucle for hace esto sin necesidad de índice.
scores = [88, 71, 95]
total = 0
for s in scores:
total = total + s
print(total) # 254
Use enumerate when you also need the index.
for i, name in enumerate(["a", "b"]):
print(i, name) # 0 a / 1 b
6.3
Listas 2-D (cuadrículas)
English
A 2-D list 二维列表 is a list of lists — a grid 网格 of rows and columns. Use two indexes: grid[row][col].
A nested loop 嵌套循环 visits every cell.
Español
A 2-D list 二维列表 es una lista de listas — una grid 网格 de filas y columnas. Usa dos índices: grid[row][col].
grid = [[1, 2], [3, 4]]
for row in grid:
for value in row:
print(value, end=" ")
print() # 1 2 3 4
6.4
Comprensiones de lista
English
A list comprehension 列表推导式 builds a new list in one line: [expression for item in sequence].
Add if to keep only some items.
Español
Una list comprehension 列表推导式 construye una nueva lista en una sola línea: [expression for item in sequence].
squares = [x * x for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
Add if to keep only some items.
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
6.5
Tuples y sets
English
A tuple 元组 is a fixed sequence in round brackets. It cannot be changed after it is made — use one for values that belong together, and unpack 解包 it into names.
A function that needs to hand back two results returns a tuple:
A set 集合 stores each value once, with no order. It is perfect for removing duplicates and for fast membership tests 成员测试.
Common mistakes
b = a does not copy a list: both names point to the same list, so changing one changes the other. Use a.copy() or a[:].
The last item is a[-1]; a[len(a)] is out of range.
append adds ONE item; use extend or + to join another list.
Building a grid with [[0]*3]*3 makes three copies of the same row. Build the rows in a loop instead.
A tuple with one item needs a comma: (5,), not (5).
A set has no order and no duplicates, so you cannot index it with s[0].
Español
Un tuple 元组 es una secuencia fija entre paréntesis redondos. No se puede cambiar después de su creación — úsalo para valores que pertenecen juntos, y desempaquetalo 解包 en nombres.
point = (3, 4)
x, y = point # unpacking
print(x, y) # 3 4
Una función que necesita devolver dos resultados devuelve un tuple:
Asigne a una clave para agregarla o para modificar una existente.
student = {"name": "Mei"}
student["score"] = 88 # add a new key
student["score"] = 90 # update the value
print(student) # {'name': 'Mei', 'score': 90}
Consultar y iterar
Use in para verificar si existe una clave. Itere sobre las claves, o sobre .items() para obtener tanto la clave como el valor.
student = {"name": "Mei", "score": 90}
print("score" in student) # True
for key, value in student.items():
print(key, "=", value)
# name = Mei
# score = 90
.get(key, default) devuelve un valor predeterminado 默认值 cuando falta la clave — sin generar error.
El código dentro se ejecuta solo cuando llamas a la función.
def define; call runs; return sends a value back
8.2
Valores de retorno
English
A function can return 返回 a value with return. The call then stands for that value.
return ends the function at once. A function with no return gives None.
Español
Una función puede devolver un valor con return. La llamada entonces equivale a ese valor.
def square(n):
return n * n
print(square(5)) # 25
print(square(3) + 1) # 10
return termina la función inmediatamente. Una función sin return devuelve None.
8.3
Parámetros, argumentos y ámbito
English
A parameter 形参 is the name in the def. An argument 实参 is the value you pass in.
A variable made inside a function is local 局部 — it exists only there. That region is its scope 作用域.
A parameter can have a default value 默认值, used when the caller leaves it out:
Español
Un parámetro es el nombre en la definición def. Un argumento es el valor que pasas.
def power(base, exp): # base, exp are parameters
return base ** exp
print(power(2, 3)) # 8 (2 and 3 are arguments)
Una variable creada dentro de una función es local: existe solo allí. Esa región es su ámbito.
def f():
x = 10 # local to f
return x
print(f()) # 10
# print(x) here would be an error: x is not defined outside f
Un parámetro puede tener un valor predeterminado, utilizado cuando quien llama omite el argumento:
def greet(name, greeting="Hello"):
return greeting + ", " + name
print(greet("Mei")) # Hello, Mei
print(greet("Sam", "Welcome")) # Welcome, Sam
8.4
Abstracción procedural
English
Procedural abstraction 过程抽象 means hiding details behind a name. You use a function by its name and what it does, not by how it works.
A good function does one job, has a clear name, and avoids repeating code.
Español
La abstracción procedural significa ocultar detalles detrás de un nombre. Usas una función por su nombre y lo que hace, no por cómo funciona internamente.
def area_of_rectangle(w, h):
return w * h
print(area_of_rectangle(4, 5)) # 20
Una buena función realiza una sola tarea, tiene un nombre claro y evita repetir código.
8.5
Módulos e importaciones
English
A module 模块 is a file of ready-made functions. Bring one in with import 导入.
Common mistakes
A function returns None unless you write return. Printing is not the same as returning.
Never use a mutable default like def f(x=[]) — the same list is shared between all calls.
A variable made inside a function is local and cannot be seen outside it.
Run a function with f(); writing f on its own only names it.
Español
Un módulo es un archivo de funciones predefinidas. Inclúyelo con import.
import random
random.seed(0) # makes the result repeatable
print(random.randint(1, 6)) # a dice roll
import math
print(math.sqrt(16)) # 4.0
Errores comunes
Una función devuelve None a menos que escribas return. Imprimir no es lo mismo que devolver.
Nunca uses un valor predeterminado mutable como def f(x=[]): la misma lista se comparte entre todas las llamadas.
Una variable creada dentro de una función es local y no puede verse desde fuera.
Ejecuta una función con f(); escribir f solo le asigna un nombre pero no la ejecuta.
9Errors, exceptions & testing · Errores, excepciones y pruebas
9.1
Errores y depuración
English
Code can fail in three ways. A syntax error 语法错误 breaks Python's rules, so it never runs. A runtime error 运行时错误 happens while running, like dividing by zero. A logic error 逻辑错误 runs but gives the wrong answer.
Python prints a traceback 回溯 showing where it failed. Read it from the bottom up.
Español
El código puede fallar de tres formas. Un error de sintaxis rompe las reglas de Python, por lo que nunca se ejecuta. Un error en tiempo de ejecución ocurre mientras el programa se ejecuta, como dividir por cero. Un error lógico se ejecuta pero da la respuesta incorrecta.
# A runtime error, caught so this block still finishes:
try:
print(10 / 0)
except ZeroDivisionError:
print("cannot divide by zero")
# cannot divide by zero
Python imprime un rastreo de pila (traceback) mostrando dónde falló. Léalo de abajo hacia arriba.
Errores comunes de Python: Sintaxis, Nombre, Tipo, Índice
9.2
try / except / raise
English
Wrap risky code in try. If it fails, except catches the exception 异常 and handles 处理 it, instead of crashing.
Catch a specific type (ValueError, ZeroDivisionError, …).
raise makes your own error on purpose.
Español
Encierre el código riesgoso en try. Si falla, except captura la excepción y la maneja, en lugar de provocar una caída del sistema.
Capture un tipo específico (ValueError, ZeroDivisionError, …).
raise genera su propio error a propósito.
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
try:
set_age(-1)
except ValueError as err:
print("error:", err)
# error: age cannot be negative
9.3
Pruebas y robustez
English
A test 测试 checks that code gives the right answer. Try normal cases and edge cases 边界情形 — empty input, zero, very large values.
Robust 健壮 code does not crash on strange input; it handles it gracefully.
Common mistakes
Do not use a bare except: — catch the specific error, e.g. except ValueError:.
A syntax error stops the whole program before it runs, so fix those first.
Test the edge cases (empty input, zero, the largest value), not just the easy one.
Español
Una prueba verifica que el código produzca la respuesta correcta. Pruebe casos normales y casos límite — entrada vacía, cero, valores muy grandes.
El código robusto no se cae con entradas extrañas; las maneja con elegancia.
Errores comunes
No use un except: sin especificar nada; capture el error específico, ej. except ValueError:.
Un error de sintaxis detiene todo el programa antes de que se ejecute, así que corríjalos primero.
Pruebe los casos límite (entrada vacía, cero, el valor más grande), no solo el fácil.
10Files · Archivos
10.1
Lectura y escritura de archivos de texto
English
A text file 文本文件 stores text on disk. Open it with open(name, mode) where mode 模式 says read or write. Always use with, which closes the file for you.
Writing
Mode "w" writes a new file and erases any old one.
Reading
Mode "r" (the default) reads. .read() returns the whole file as one string.
Line by line
Loop over the file to get one line at a time. .strip() removes 去除 the newline 换行符 at the end.
Appending
Mode "a" appends 追加 — it adds to the end without erasing.
Mode
Meaning
"r"
read (default)
"w"
write (erases first)
"a"
append (add to the end)
Common mistakes
Always close a file, or use with open(...) as f: which closes it for you.
read() gives the whole file as one string, and each line still ends with \n.
Opening with "w" erases the file first; use "a" to add to the end.
Español
Un archivo de texto 文本文件 almacena texto en el disco. Ábrelo con open(name, mode) donde mode 模式 indica leer o escribir. Siempre usa with, que cierra el archivo por ti.
Escritura
El modo "w" escribe un archivo nuevo y borra cualquier archivo anterior.
with open("notes.txt", "w") as f:
f.write("first line\n")
f.write("second line\n")
print("saved") # saved
Lectura
El modo "r" (el predeterminado) lee. .read() devuelve todo el archivo como una sola cadena.
with open("notes.txt", "w") as f:
f.write("hello\nworld\n")
with open("notes.txt") as f:
print(f.read().strip()) # hello / world
Línea por línea
Recorre el archivo para obtener una línea a la vez. .strip() elimina 去除 el salto de línea 换行符 al final.
with open("data.txt", "w") as f:
f.write("Mei,88\nSam,71\n")
with open("data.txt") as f:
for line in f:
name, score = line.strip().split(",")
print(name, "scored", score)
# Mei scored 88
# Sam scored 71
Append
El modo "a" appendea 追加 — añade al final sin borrar.
with open("log.txt", "w") as f:
f.write("line 1\n")
with open("log.txt", "a") as f:
f.write("line 2\n")
with open("log.txt") as f:
print(f.read().strip()) # line 1 / line 2
Mode
Significado
"r"
read (predeterminado)
"w"
write (borra primero)
"a"
append (añadir al final)
Errores comunes
Cierra siempre un archivo, o usa with open(...) as f: que lo cierra por ti.
read() da todo el archivo como una sola cadena, y cada línea aún termina con \n.
Abrir con "w" borra el archivo primero; usa "a" para añadir al final.
open → read/write → close (with auto-closes)
11Algorithm design · Diseño de algoritmos
11.1
Algoritmos y descomposición
English
An algorithm 算法 is a clear list of steps that solves a problem. Decomposition 分解 means breaking a big problem into smaller parts you can solve one at a time.
Abstraction 抽象 means ignoring detail: you use largest(...) without re-reading how it works.
Español
Un algoritmo 算法 es una lista clara de pasos que resuelve un problema. La descomposición 分解 significa dividir un problema grande en partes más pequeñas que se pueden resolver una a la vez.
# Algorithm: find the largest number in a list
def largest(nums):
best = nums[0]
for n in nums:
if n > best:
best = n
return best
print(largest([3, 9, 2, 7])) # 9
La abstracción 抽象 significa ignorar los detalles: usas largest(...) sin tener que releer cómo funciona internamente.
11.2
Pseudocódigo y diagramas de flujo
English
Pseudocode 伪代码 is plain, structured English for an algorithm, written before the real code. It is not run.
A flowchart 流程图 draws the same plan: a box for each step, a diamond for each decision 判断, and arrows for the order.
Español
El pseudocódigo 伪代码 es un inglés estructurado y sencillo para describir un algoritmo, escrito antes del código real. No se ejecuta.
SET best TO first number
FOR Each number n
IF n > best
THEN
SET best TO n
OUTPUT best
Un diagrama de flujo 流程图 dibuja el mismo plan: un recuadro para cada paso, un rombo para cada decisión 判断, y flechas para indicar el orden.
11.3
Recursión y pila de llamadas
English
Recursion 递归 is when a function calls itself. It needs a base case 基准情形 (a simple input that returns at once) and a recursive case 递归情形 (it calls itself on a smaller input).
Each paused call sits on the call stack 调用栈 until the call above it returns.
Common mistakes
Recursion needs a base case, or it calls itself forever and crashes the call stack.
Pseudocode is for planning — it need not run, but every step must be unambiguous.
Break a big problem into small named steps before you write any code.
Español
La recursión 递归 ocurre cuando una función se llama a sí misma. Necesita un caso base 基准情形 (una entrada simple que devuelve inmediatamente) y un caso recursivo 递归情形 (se llama a sí misma con una entrada más pequeña).
La pila de llamadas para factorial(3): cada llamada espera, luego retorna en orden inverso
def fact(n):
return 1 if n <= 1 else n * fact(n - 1)
print(fact(5)) # 120
Cada llamada pausada permanece en la pila de llamadas 调用栈 hasta que la llamada superior a ella retorna.
Errores comunes
La recursión necesita un caso base; de lo contrario, se llamará a sí misma indefinidamente y colapsará la pila de llamadas.
El pseudocódigo sirve para planificar — no necesita ejecutarse, pero cada paso debe ser inequívoco.
Divide un problema grande en pasos pequeños y nombrados antes de escribir cualquier código.
12Data structures · Estructuras de datos
12.1
Tipos de Datos Abstractos (ADT)
English
An abstract data type 抽象数据类型 (ADT) describes some data plus the operations on it, separate from how it is built. You use it through its operations, not through its inner storage.
Español
Un tipo de dato abstracto (ADT) describe datos junto con las operaciones sobre ellos, independientemente de cómo se implementen internamente. Se accede a él mediante sus operaciones, no a través de su almacenamiento interno.
# A stack ADT, built on a list
s = []
s.append(1) # add
s.append(2)
print(s.pop()) # 2 (remove the most recent)
12.2
Pilas (Stacks)
English
A stack 栈 is last-in, first-out (LIFO 后进先出). You push 压入 onto the top and pop 弹出 from the top.
Español
Una pila es último-en, primero-salido (LIFO). Empujar (push) ocurre en la parte superior y popear (pop) también desde la parte superior.
Una pila elimina desde la parte superior (LIFO); una cola elimina desde el frente (FIFO)
stack = []
stack.append("a")
stack.append("b")
print(stack.pop()) # b
print(stack.pop()) # a
12.3
Colas (Queues)
English
A queue 队列 is first-in, first-out (FIFO 先进先出). You enqueue 入队 at the back and dequeue 出队 from the front.
Español
Una cola es primero-en, primero-salido (FIFO). Encolar (enqueue) ocurre en la parte trasera y desencolar (dequeue) ocurre desde el frente.
queue = []
queue.append("a") # enqueue
queue.append("b")
print(queue.pop(0)) # a (dequeue the front)
print(queue.pop(0)) # b
12.4
Listas enlazadas
English
A linked list 链表 is a chain of nodes 节点. Each node holds data and a pointer 指针 to the next node; the last points to None.
Español
Una lista enlazada es una cadena de nodos. Cada nodo contiene datos y un puntero al siguiente nodo; el último apunta a None.
Una lista enlazada: cada nodo contiene datos y un puntero al siguiente nodo, terminando en None
n3 = {"data": 3, "next": None}
n2 = {"data": 2, "next": n3}
n1 = {"data": 1, "next": n2}
node = n1
while node is not None: # traverse to the end
print(node["data"])
node = node["next"]
# 1 2 3
12.5
Tablas hash
English
A hash table 哈希表 maps a key to a slot with a hash function 哈希函数. Two keys can land in the same slot — a collision 冲突. Python's dict is a hash table, so lookup is fast.
Español
Una tabla hash mapea una clave a una ranura mediante una función hash. Dos claves pueden caer en la misma ranura — esto se denomina colisión. El tipo dict de Python es una tabla hash, por lo que la búsqueda es rápida.
Una función hash mapea cada clave a una ranura; dos claves pueden colisionar en una misma ranura
A binary search tree 二叉搜索树 (BST) keeps order: every left child is smaller than its node, every right child is larger. Search stays fast.
Español
Un árbol binario de búsqueda (BST) mantiene un orden: cada hijo izquierdo es menor que su nodo, y cada hijo derecho es mayor. La búsqueda permanece rápida.
Un árbol binario de búsqueda: los valores menores van a la izquierda, los mayores van a la derecha
def insert(root, val):
if root is None:
return {"val": val, "left": None, "right": None}
if val < root["val"]:
root["left"] = insert(root["left"], val)
else:
root["right"] = insert(root["right"], val)
return root
def inorder(root):
if root is None:
return []
return inorder(root["left"]) + [root["val"]] + inorder(root["right"])
tree = None
for v in [5, 3, 8, 1, 4]:
tree = insert(tree, v)
print(inorder(tree)) # [1, 3, 4, 5, 8]
12.7
Grafos
English
A graph 图 is a set of vertices 顶点 joined by edges 边. An adjacency list 邻接表 — a dict of neighbour lists — is a common way to store one.
Common mistakes
A stack is last-in-first-out; a queue is first-in-first-out. Do not mix them up.
Check whether a structure is empty before you pop or dequeue from it.
In a linked list, losing the head pointer loses the whole list.
Español
Un grafo es un conjunto de vértices unidos por aristas. Una lista de adyacencia — un diccionario de listas de vecinos — es una forma común de almacenarlo.
Un grafo de vértices y aristas, con su forma de lista de adyacencia
graph = {"A": ["B", "D"], "B": ["A", "C"], "C": ["B", "D"], "D": ["A", "C"]}
for vertex in graph:
print(vertex, "->", graph[vertex])
# A -> ['B', 'D'] (and so on for B, C, D)
Errores comunes
Una pila es último-en-primer-salido; una cola es primero-en-primer-salido. No los confunda.
Verifique si una estructura está vacía antes de hacer pop o dequeue en ella.
En una lista enlazada, perder el puntero head (cabeza) hace perder toda la lista.
13Searching, sorting & efficiency · Búsqueda, ordenamiento y eficiencia
13.1
Búsqueda lineal y binaria
English
A search 查找 finds where a value is. Linear search 线性查找 checks each item in turn, so it works on any list.
Binary search 二分查找 is much faster but needs a sorted list. It halves the range each step.
Español
Una búsqueda busca dónde se encuentra un valor. La búsqueda lineal revisa cada elemento en secuencia, por lo que funciona con cualquier lista.
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1 # not found
print(linear_search([4, 8, 2, 9], 2)) # 2
La búsqueda binaria es mucho más rápida pero necesita una lista ordenada. Reduce a la mitad el rango en cada paso.
def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9], 7)) # 3
La búsqueda binaria reduce a la mitad el rango en cada paso — O(log n) en una lista ordenada
13.2
Ordenamiento (burbuja e inserción)
English
To sort 排序 is to put items in order. Bubble sort 冒泡排序 repeatedly swaps 交换 neighbours that are in the wrong order.
Insertion sort 插入排序 builds a sorted part one item at a time, sliding each new item back into its place:
In real code, use Python's built-in sorted():
Español
Ordenar es colocar los elementos en un orden específico. El ordenamiento burbuja intercambia repetidamente vecinos que están en el orden incorrecto.
def bubble_sort(a):
a = a[:] # work on a copy
for i in range(len(a)):
for j in range(len(a) - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
return a
print(bubble_sort([5, 2, 4, 1])) # [1, 2, 4, 5]
El ordenamiento por inserción construye una parte ordenada elemento a elemento, desplazando cada nuevo elemento hacia atrás hasta su lugar:
def insertion_sort(a):
a = a[:] # work on a copy
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key: # shift bigger values right
a[j + 1] = a[j]
j -= 1
a[j + 1] = key # drop key into the gap
return a
print(insertion_sort([5, 2, 4, 1])) # [1, 2, 4, 5]
En código real, use sorted() de Python:
print(sorted([5, 2, 4, 1])) # [1, 2, 4, 5]
13.3
Eficiencia algorítmica
English
Efficiency 效率 asks how the work grows as the input grows. We describe it with Big-O 大O记号.
Big-O
Name
Example
$O(1)$
constant
look up a dict key
$O(\log n)$
logarithmic
binary search
$O(n)$
linear
linear search
$O(n^2)$
quadratic
bubble sort
Español
La eficiencia pregunta cómo crece el trabajo conforme crece la entrada. Lo describimos con Big-O.
Cómo crece el número de pasos con el tamaño de la entrada para las complejidades comunes
Big-O
Nombre
Ejemplo
$O(1)$
constante
buscar una clave en un diccionario
$O(\log n)$
logarítmica
búsqueda binaria
$O(n)$
lineal
búsqueda lineal
$O(n^2)$
cuadrática
ordenamiento burbuja
def steps(n): # how many steps a linear scan takes
count = 0
for i in range(n):
count = count + 1
return count
print(steps(100)) # 100 -> O(n)
13.4
Aleatoriedad y simulación
English
The random module makes random numbers. Use a seed 种子 to make results repeatable. A simulation 模拟 runs many random trials to estimate an answer.
Common mistakes
Binary search only works on a sorted list.
Big-O tells you how the time GROWS, not the exact time; an O(n²) method beats O(n) only for tiny inputs.
Bubble sort is O(n²) — fine for learning, but slow on large lists.
Español
El módulo random genera números aleatorios. Use una semilla para hacer que los resultados sean reproducibles. Una simulación ejecuta muchas pruebas aleatorias para estimar una respuesta.
import random
random.seed(0)
rolls = [random.randint(1, 6) for _ in range(1000)]
print(rolls.count(6)) # about 1/6 of 1000
Errores comunes
La búsqueda binaria solo funciona en una lista ordenada.
Big-O indica cómo crece el tiempo, no el tiempo exacto; un método O(n²) supera a uno O(n) solo para entradas muy pequeñas.
El ordenamiento burbuja es O(n²) — adecuado para aprender, pero lento en listas grandes.
14OOP & paradigms · POO y paradigmas
14.1
Clases y objetos
English
A class 类 is a blueprint. An object 对象 is one thing built from it (an instance 实例). __init__ is the constructor 构造方法 that sets up each object; self is the object itself.
name is an attribute 属性 (data on the object); speak is a method 方法 (an action).
Add __str__ to control what print(obj) shows:
Español
Una clase 类 es una plantilla. Un objeto 对象 es algo construido a partir de ella (una instancia 实例). __init__ es el constructor 构造方法 que configura cada objeto; self es el propio objeto.
class Dog:
def __init__(self, name):
self.name = name # an attribute
def speak(self):
return self.name + " says woof"
d = Dog("Rex")
print(d.speak()) # Rex says woof
name es un atributo 属性 (datos en el objeto); speak es un método 方法 (una acción).
Agrega __str__ para controlar lo que muestra print(obj):
class Dog:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Dog named {self.name}"
print(Dog("Rex")) # Dog named Rex
Una clase es una plantilla; al llamarla se crea un objeto
14.2
Herencia, encapsulamiento y polimorfismo
English
Inheritance 继承 lets a subclass 子类 reuse a superclass 父类. Use super() to call the parent; override 重写 a method to change it.
Encapsulation 封装 hides data behind methods; a leading underscore marks it private 私有.
Polymorphism 多态 means one name, many behaviours — the right speak runs for each object.
Español
La herencia 继承 permite que una subclase 子类 reutilice una superclase 父类. Usa super() para llamar al padre; sobreescribe 重写 un método para cambiarlo.
class Animal:
def speak(self):
return "some sound"
class Cat(Animal):
def speak(self): # override
return "meow"
print(Cat().speak()) # meow
El encapsulamiento 封装 oculta los datos detrás de métodos; un guion bajo inicial lo marca como privado 私有.
class Account:
def __init__(self):
self._balance = 0 # private
def deposit(self, n):
self._balance += n
def balance(self):
return self._balance
a = Account()
a.deposit(50)
print(a.balance()) # 50
El polimorfismo 多态 significa un mismo nombre con muchos comportamientos — el speak correcto se ejecuta para cada objeto.
class Cat:
def speak(self):
return "meow"
class Cow:
def speak(self):
return "moo"
for animal in [Cat(), Cow()]:
print(animal.speak()) # meow, then moo
14.3
Paradigmas de programación
English
A paradigm 范式 is a style of writing programs. Procedural 过程式 code is a sequence of steps and functions. Object-oriented 面向对象 code groups data and methods into objects. Declarative 声明式 code says what you want, not how (a list comprehension or SQL).
Common mistakes
Every method needs self as its first parameter.
__init__ sets up a new object and runs automatically when you create one.
Two objects of the same class have separate attributes; changing one does not change the other.
Español
Un paradigma 范式 es un estilo de escribir programas. El código procedural 过程式 es una secuencia de pasos y funciones. El código orientado a objetos 面向对象 agrupa datos y métodos en objetos. El código declarativo 声明式 dice qué quieres, no cómo (una comprensión de lista o SQL).
def total(nums): # procedural
t = 0
for n in nums:
t += n
return t
print(total([1, 2, 3])) # 6
print(sum([1, 2, 3])) # 6 (declarative: same result)
Errores comunes
Todo método necesita self como su primer parámetro.
__init__ configura un nuevo objeto y se ejecuta automáticamente al crearlo.
Dos objetos de la misma clase tienen atributos separados; modificar uno no modifica el otro.
15Data representation · Representación de datos
15.1
Bits y binario
English
A bit 比特 is a single 0 or 1. Binary 二进制 is the base-2 number system: each place is worth twice the one to its right (1, 2, 4, 8, …). Denary 十进制 (base-10) is our normal numbers.
8 bits make a byte 字节. A fixed width can overflow 溢出 (wrap around) when the number is too big.
Hexadecimal 十六进制 (base 16) is a compact way to read binary: one hex digit stands for exactly four bits. Python writes hex with 0x:
Español
Un bit (比特) es un único 0 o 1. El binario (二进制) es el sistema numérico de base 2: cada posición vale el doble que la de su derecha (1, 2, 4, 8, …). El decimal (十进制) son nuestros números habituales.
8 bits forman un byte (字节). Un ancho fijo puede desbordarse (溢出) (dar la vuelta al número) cuando este es demasiado grande.
x = 250
x = (x + 10) % 256 # one byte wraps at 256
print(x) # 4
El hexadecimal (十六进制) (base 16) es una forma compacta de leer binario: un dígito hexadecimal equivale exactamente a cuatro bits. Python escribe hexadecimales con 0x:
Compression 压缩 makes data smaller. Lossless 无损 compression keeps every bit, so you rebuild the original exactly. Lossy 有损 compression throws away detail — smaller but not exact — and is used for photos and music.
Run-length encoding 游程编码 is a simple lossless method: store a run 游程 (a repeat) as a count plus the value.
Common mistakes
n bits store 2**n different values, from 0 up to 2**n - 1.
Lossy compression throws away detail and cannot be undone; lossless can be reversed exactly.
Español
La compresión (压缩) hace que los datos sean más pequeños. La compresión sin pérdida (无损) conserva todos los bits, por lo que se reconstruye el original exactamente. La compresión con pérdida (有损) descarta detalles —es más pequeña pero no exacta— y se utiliza para fotos y música.
La codificación por recuento de secuencias (游程编码) es un método simple sin pérdida: almacena una secuencia (游程) (una repetición) como un contador más el valor.
def rle(text):
out = ""
i = 0
while i < len(text):
run = 1
while i + run < len(text) and text[i + run] == text[i]:
run += 1
out += str(run) + text[i]
i += run
return out
print(rle("AAAABBBCCD")) # 4A3B2C1D
Errores comunes
n bits almacenan 2**n valores diferentes, desde 0 hasta 2**n - 1.
La compresión con pérdida elimina detalles y no puede revertirse; la compresión sin pérdida se puede invertir exactamente.
16Computing concepts · Conceptos de computación
16.1
¿Qué es la computación y el ciclo de diseño
English
Computing 计算 means solving problems with computers: input, process, output. Good software is built in a design cycle 设计循环 — plan, write, test, improve — repeated many times.
Break a problem down, build a small part, test it, then add more.
Programmers work in teams and reuse each other's code.
Español
La computación significa resolver problemas con computadoras: entrada, procesamiento y salida. El buen software se construye mediante un ciclo de diseño —planificar, escribir, probar, mejorar— que se repite muchas veces.
Descomponga un problema, construya una parte pequeña, pruébela y luego agregue más.
Los programadores trabajan en equipos y reutilizan el código de sus compañeros.
16.2
Internet
English
The Internet 互联网 is a network 网络 of networks. Data is split into packets 数据包 that travel separately and are put back together at the other end. Shared rules called protocols 协议 (such as TCP/IP) make this work. If one path breaks, packets take another route — this is redundancy 冗余, which gives fault tolerance 容错.
Layer
Job
HTTP
request and send web pages
TCP
reliable delivery, in order
IP
addressing and routing
Español
Internet es una red de redes. Los datos se dividen en paquetes que viajan por separado y se reconstruyen en el extremo destino. Reglas compartidas llamadas protocolos (como TCP/IP) hacen posible esto. Si se interrumpe una ruta, los paquetes toman otra trayectoria; esto es redundancia, lo que otorga tolerancia a fallos.
Un mapa de Internet: cada línea representa una ruta entre dos redes
Capa
Función
HTTP
solicitar y enviar páginas web
TCP
entrega confiable, en orden
IP
direccionamiento y enrutamiento
16.3
Computación paralela y distribuida
English
Sequential 顺序 code does one step at a time. Parallel 并行 computing does several steps at once on many cores 核心, which can give a speedup 加速. Distributed 分布式 computing spreads the work across many computers, such as a cloud.
Not everything can run in parallel: some steps must wait for an earlier result.
Español
El código secuencial ejecuta un paso a la vez. La computación paralela realiza varios pasos simultáneamente en múltiples núcleos, lo que puede generar una aceleración. La computación distribuida reparte la carga de trabajo entre varias computadoras, como las de una nube.
No todo puede ejecutarse en paralelo: algunos pasos deben esperar un resultado previo.
16.4
Impacto de la computación
English
Computing brings both benefits and harms. The digital divide 数字鸿沟 means not everyone has equal access to it. Software can carry bias 偏见 from the data it learns from. Respect intellectual property 知识产权 (licences), and protect people's personal data 个人数据 and privacy 隐私.
Common mistakes
The Internet and the World Wide Web are not the same: the Web is one service that runs on top of the Internet.
More processor cores help only if the work can be split into parts that run at the same time.
Español
La computación conlleva tanto beneficios como perjuicios. La brecha digital significa que no todos tienen acceso igualitario a ella. El software puede transmitir sesgos derivados de los datos con los que aprende. Respete la propiedad intelectual (licencias), y proteja los datos personales y la privacidad de las personas.
Errores comunes
Internet y World Wide Web no son lo mismo: la Web es un servicio que funciona sobre Internet.
Más núcleos del procesador solo ayudan si la tarea puede dividirse en partes que se ejecuten al mismo tiempo.
17Putting it together · Poniéndolo en práctica
17.1
Mini-proyectos de extremo a extremo
English
A mini-project 小项目 combines earlier ideas: data in a list, a function with selection inside a loop, and printed output. This is also the shape of the AP Create Performance Task.
Project: average mark
Project: count passes
Project: filter to a new list
The AP Create Task wants a list, a parameterised procedure 过程 that uses selection 选择 and iteration 迭代, and some input/output. Each project above is exactly that shape — build small pieces, then join them.
Common mistakes
Build in small steps and test each part before moving on — do not write it all at once.
Read the whole task first, then plan the input → process → output before you code.
Español
Un mini-proyecto 小项目 combina ideas anteriores: datos en una lista, una función con selección dentro de un bucle y salida impresa. Esta también es la estructura de la Tarea de Rendimiento del AP Create.
def count_passes(marks, pass_mark=60):
passes = 0
for m in marks: # iteration
if m >= pass_mark: # selection
passes += 1
return passes
print(count_passes([88, 50, 95, 60])) # 3
Proyecto: filtrar a una nueva lista
def merit(marks):
return [m for m in marks if m >= 80]
print(merit([88, 71, 95, 60])) # [88, 95]
La tarea AP Create pide una lista, un procedimiento parametrizado 过程 que utilice selección 选择 e iteración 迭代, y alguna entrada/salida. Cada uno de los proyectos anteriores tiene exactamente esa estructura: construye piezas pequeñas y luego únelas.
Errores comunes
Construye paso a paso y prueba cada parte antes de pasar a la siguiente; no escribas todo de una vez.
Lee toda la tarea primero, luego planifica la entrada → proceso → salida antes de escribir el código.
Mini-proyecto: datos → función → resultado impreso
Pick one and the site follows you — notes, papers, videos and practice all open on it. · Selecciona uno y el sitio te sigue — notas, documentos, videos y práctica se abren en él.
Type to search notes, lessons, code, vocabulary and past-paper questions across every subject. · Escribe para buscar notas, lecciones, código, vocabulario y preguntas de exámenes anteriores en todas las materias.