This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · Esta página precisa de um navegador recente (com suporte a SharedArrayBuffer). Por favor, atualize Chrome, Edge, Firefox ou Safari para a versão mais recente.
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.
Português
Python executa seu código uma linha por vez. Cada linha é uma declaração 语句. Um programa 程序 é apenas uma lista de declarações que rodam de cima para baixo.
A função print() exibe texto na tela. Isso é chamado output 输出. Texto entre aspas é uma string 字符串.
print("Hello, world!")
print("I am learning Python")
Cada print() inicia uma nova linha.
As aspas podem ser simples "double" ou duplas 'single' — ambas criam uma string.
Um programa não faz nada até você executá-lo.
O código-fonte passa pelo interpretador para produzir output
1.2
Comentários & estilo de 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 错误.
Português
Um comentário 注释 começa com #. Python ignora tudo depois do # naquela linha. Comentários explicam seu código para pessoas; eles não mudam o que o código faz.
# This line is a note for humans
print("Hi") # you can also comment at the end of a line
Bom estilo torna o código fácil de ler:
Use nomes claros que digam o que um valor significa.
Coloque uma declaração por linha.
Não adicione espaços no início de uma linha normal. Em Python, espaçamento no início (indentation 缩进) tem um significado especial, então um espaço errado gera um erro 错误.
1.3
Entrada, processamento, saída
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.
Português
Muitos programas seguem um plano simples: entrada 输入 → processo → saída. Você obtém alguns dados, faz algo com eles, depois mostra um resultado.
A função input() lê o texto que o usuário digita. Ela sempre retorna uma string.
name = input("What is your name? ")
print("Hello, " + name)
input() espera o usuário digitar e pressionar Enter.
Armazene o texto digitado em uma variável 变量 para usá-la depois.
Como input() retorna uma string, altere-a com int(...) primeiro se precisar de um número.
Erros comuns
Esquecer as aspas: print(Hello) procura uma variável chamada Hello e levanta um NameError. Texto precisa de aspas: print("Hello").
Um espaço solto no início de uma linha: Python lê a indentação como estrutura, então levanta um IndentationError.
Assumir que input() retorna um número. Ela sempre retorna uma string, então envolva-a em int(...) antes de fazer qualquer matemática.
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).
Português
Uma variável 变量 é um nome para um valor 值. Você cria uma com =, que é chamado de atribuição 赋值. O nome vai à esquerda; o valor vai à direita.
age = 17
name = "Mei"
price = 9.99
print(age, name, price)
Agora age contém 17. Use o nome onde quer que precise do valor, e altere-o depois:
age = 17
age = age + 1 # age is now 18
print(age)
Cada nome de variável aponta para um valor na memória
O sinal = não significa "igual". Significa "armazenar o lado direito sob o nome da esquerda".
Para testar se dois valores são iguais, use == (veja abaixo).
2.2
Números: int & 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.
Português
Python tem dois tipos principais de números. Um inteiro 整数 (int) é um número inteiro como 17. Um float 浮点数 (float) tem ponto decimal como 9.99.
Estes operadores 运算符 funcionam em números:
Operador
Significado
Exemplo
Resultado
+
somar
3 + 2
5
-
subtrair
3 - 2
1
*
multiplicar
3 * 2
6
/
dividir (sempre float)
7 / 2
3.5
//
divisão inteira
7 // 2
3
%
resto (módulo)
7 % 2
1
**
potência
2 ** 3
8
/ sempre dá um float, então 4 / 2 é 2.0.
// e % andam juntos: 17 // 5 é 3, e 17 % 5 é 2.
2.3
Expressões & conversão 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).
Português
Uma expressão 表达式 é qualquer coisa que tem um valor, como 3 + 4 * 2. Python usa a ordem matemática normal (* e / antes de + e -); adicione parênteses para deixar a ordem clara.
input() retorna uma string, então converta-a antes de fazer matemática. Mudar um valor de um tipo para outro é conversão 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") falha, então converta apenas texto que pareça um número.
Misturar tipos também falha: "age: " + 17 é um erro; escreva "age: " + str(17).
2.4
Booleanos & comparação
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.
Português
Um Boolean 布尔值 é um de apenas dois valores: True ou False. Uma comparação 比较 retorna um Boolean.
A comparison 比较 gives a Boolean 布尔值 — either True or False.
Português
Um programa escolhe o que fazer com base em if. Ele executa um bloco indentado apenas quando uma condição é verdadeira. A linha if termina com dois-pontos.
score = 72
if score >= 60:
print("pass")
# pass
Adicione elif (else-if) para mais casos e else para "qualquer outra coisa". Python executa apenas o primeiro ramo verdadeiro e ignora os demais.
score = 72
if score >= 80:
print("A")
elif score >= 60:
print("B")
else:
print("fail")
# B
grid = [[1, 2], [3, 4]]
for row in grid:
for value in row:
print(value, end=" ")
print() # 1 2 3 4
6.4
List comprehensions · Compreensão de listas
English
A list comprehension 列表推导式 builds a new list in one line: [expression for item in sequence].
Add if to keep only some items.
Português
Um list comprehension constrói uma nova lista em uma linha: [expression for item in sequence].
squares = [x * x for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
Adicione if para manter apenas alguns itens.
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
6.5
Tuples & sets · Tuplas & conjuntos
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].
Português
Um tuple é uma sequência fixa entre parênteses redondos. Não pode ser alterado após criado — use-o para valores que pertencem juntos e desempacote-o em nomes.
point = (3, 4)
x, y = point # unpacking
print(x, y) # 3 4
Uma função que precisa devolver dois resultados retorna um tuple:
Atribua a uma chave para adicioná-la ou alterar uma existente.
student = {"name": "Mei"}
student["score"] = 88 # add a new key
student["score"] = 90 # update the value
print(student) # {'name': 'Mei', 'score': 90}
Verificar e iterar
Use in para testar se uma chave existe. Itere sobre as chaves, ou sobre .items() para obter tanto a chave quanto o 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) retorna um valor padrão quando a chave está ausente — sem erro.
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.
Português
O código pode falhar de três maneiras. Um erro de sintaxe quebra as regras do Python, então nunca executa. Um erro de tempo de execução ocorre durante a execução, como divisão por zero. Um erro lógico executa mas dá a resposta errada.
# 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 um traceback mostrando onde falhou. Leia-o de baixo para cima.
Erros comuns do Python: Syntax, Name, Type, Index
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.
Português
Envolva código arriscado em try. Se falhar, except captura a exceção e a trata, em vez de travar.
Capture um tipo específico (ValueError, ZeroDivisionError, …).
raise gera seu próprio erro propositalmente.
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
Testing & robustness · Testes & 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.
Português
Um teste 测试 verifica se o código produz a resposta correta. Teste casos normais e casos de borda 边界情形 — entrada vazia, zero, valores muito grandes.
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.
Português
Um arquivo de texto 文本文件 armazena texto em disco. Abra-o com open(name, mode) onde mode 模式 diz para ler ou escrever. Sempre use with, que fecha o arquivo por você.
Escrevendo
Mode "w" escreve um novo arquivo e apaga qualquer antigo.
with open("notes.txt", "w") as f:
f.write("first line\n")
f.write("second line\n")
print("saved") # saved
Lendo
Mode "r" (o padrão) lê. .read() retorna todo o arquivo como uma única string.
with open("notes.txt", "w") as f:
f.write("hello\nworld\n")
with open("notes.txt") as f:
print(f.read().strip()) # hello / world
Linha por linha
Faça loop sobre o arquivo para obter uma linha de cada vez. .strip() remove 去除 o newline 换行符 no 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
Mode "a" append 追加 — adiciona ao final sem apagar.
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 (padrão)
"w"
write (apaga primeiro)
"a"
append (adicionar ao final)
Erros comuns
Sempre feche um arquivo, ou use with open(...) as f: que o fecha por você.
read() dá todo o arquivo como uma única string, e cada linha ainda termina com \n.
Abrir com "w" apaga o arquivo primeiro; use "a" para adicionar ao final.
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.
Português
Um algoritmo 算法 é uma lista clara de passos que resolve um problema. Decomposição 分解 significa quebrar um grande problema em partes menores que você pode resolver uma de cada 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
Abstração 抽象 significa ignorar detalhes: você usa largest(...) sem reler como funciona.
11.2
Pseudocódigo & fluxogramas
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.
Português
Pseudocódigo 伪代码 é inglês estruturado simples para um algoritmo, escrito antes do código real. Ele não é executado.
SET best TO first number
FOR Each number n
IF n > best
THEN
SET best TO n
OUTPUT best
Um fluxograma 流程图 desenha o mesmo plano: uma caixa para cada passo, um losango para cada decisão 判断, e setas para a ordem.
11.3
Recursão & pilha de chamadas
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.
Português
Recursão 递归 é quando uma função se chama. Ela precisa de um caso base 基准情形 (uma entrada simples que retorna imediatamente) e um caso recursivo 递归情形 (ela se chama com uma entrada menor).
A pilha de chamadas para factorial(3): cada chamada espera, depois retorna em ordem inversa
def fact(n):
return 1 if n <= 1 else n * fact(n - 1)
print(fact(5)) # 120
Cada chamada pausada fica na call stack 调用栈 até a chamada acima dela retornar.
Erros comuns
Recursão precisa de um caso base, ou ela se chama infinitamente e quebra a call stack.
Pseudocódigo é para planejamento — ele não precisa rodar, mas cada passo deve ser inequívoco.
Quebre um grande problema em passos pequenos nomeados antes de escrever qualquer código.
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.
Português
Um tipo de dado abstrato 抽象数据类型 (ADT) descreve alguns dados mais as operações sobre eles, separado de como é construído. Você o usa através de suas operações, não através de seu armazenamento 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
Pilhas
English
A stack 栈 is last-in, first-out (LIFO 后进先出). You push 压入 onto the top and pop 弹出 from the top.
Português
Uma pilha 栈 é last-in, first-out (LIFO 后进先出). Você push 压入 no topo e pop 弹出 do topo.
Uma pilha remove do topo (LIFO); uma fila remove da frente (FIFO)
stack = []
stack.append("a")
stack.append("b")
print(stack.pop()) # b
print(stack.pop()) # a
12.3
Filas
English
A queue 队列 is first-in, first-out (FIFO 先进先出). You enqueue 入队 at the back and dequeue 出队 from the front.
Português
Uma fila 队列 é first-in, first-out (FIFO 先进先出). Você enqueue 入队 na traseira e dequeue 出队 da 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 encadeadas
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.
Português
Uma linked list 链表 é uma cadeia de nodes 节点. Cada node segura dados e um pointer 指针 para o próximo node; o último aponta para None.
Uma lista encadeada: cada nó contém dados e um ponteiro para o próximo nó, terminando em 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
Tabelas 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.
Português
Uma tabela hash 哈希表 mapeia uma key para uma slot com uma hash function 哈希函数. Duas keys podem cair na mesma slot — uma collision 冲突. Python's dict é uma tabela hash, então lookup é rápido.
Uma função hash mapeia cada chave para um slot; duas chaves podem colidir em um único slot
A binary search tree 二叉搜索树 (BST) keeps order: every left child is smaller than its node, every right child is larger. Search stays fast.
Português
Uma binary search tree 二叉搜索树 (BST) mantém ordem: todo filho esquerdo é menor que seu nó, todo filho direito é maior. Search permanece rápido.
Uma árvore de busca binária: valores menores vão para a esquerda, valores maiores vão para a direita
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.
Português
Um graph 图 é um conjunto de vertices 顶点 unidos por edges 边. Uma adjacency list 邻接表 — um dict de listas de vizinhos — é uma forma comum de armazenar uma.
Um gráfico de vértices e arestas, em sua forma de lista de adjacência
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)
Erros comuns
A stack é last-in-first-out; a queue é first-in-first-out. Não as misture.
Verifique se uma estrutura está vazia antes de pop ou dequeue dela.
Em uma lista encadeada, perder o ponteiro head perde toda a lista.
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.
Português
Um search 查找 encontra onde um valor está. Linear search 线性查找 verifica cada item por vez, então funciona em qualquer 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
Binary search 二分查找 é muito mais rápido mas precisa de uma lista sorted. Ela divide o range pela metade a cada passo.
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
A busca binária reduz o intervalo pela metade a cada etapa — O(log n) em uma lista ordenada
13.2
Ordenação (bubble & insertion)
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():
Português
Ordenar 排序 é colocar itens em ordem. Bubble sort 冒泡排序 troca repetidamente neighbours que estão na ordem errada.
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]
Insertion sort 插入排序 constrói uma parte sorted item por item, deslizando cada novo item de volta para seu 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]
Em código real, use o built-in Python sorted():
print(sorted([5, 2, 4, 1])) # [1, 2, 4, 5]
13.3
Eficiência 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
Português
Eficiência 效率 pergunta como o trabalho cresce conforme a entrada cresce. Descrevemos isso com Big-O 大O记号.
Como o número de etapas cresce com o tamanho da entrada para complexidades comuns
Big-O
Nome
Exemplo
$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
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
Aleatoriedade & simulação
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.
Português
O módulo random faz números aleatórios. Use um seed 种子 para tornar resultados reprodutíveis. Uma simulation 模拟 roda muitos trials aleatórios para estimar uma resposta.
import random
random.seed(0)
rolls = [random.randint(1, 6) for _ in range(1000)]
print(rolls.count(6)) # about 1/6 of 1000
Erros comuns
Binary search só funciona em uma lista sorted.
Big-O diz como o tempo CRESCE, não o tempo exato; um método O(n²) bate O(n) apenas para entradas minúsculas.
Bubble sort é O(n²) — bom para aprender, mas lento em listas grandes.
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:
Português
Uma class 类 é um blueprint. Um object 对象 é uma coisa construída a partir dele (um instance 实例). __init__ é o constructor 构造方法 que configura cada objeto; self é o objeto em si.
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 é um attribute 属性 (dados no objeto); speak é um method 方法 (uma ação).
Adicione __str__ para controlar o que print(obj) mostra:
class Dog:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Dog named {self.name}"
print(Dog("Rex")) # Dog named Rex
Uma classe é um modelo; chamá-la cria um objeto
14.2
Herança, encapsulamento & 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.
Português
Herança 继承 deixa um subclass 子类 reutilizar um superclass 父类. Use super() para chamar o parent; override 重写 um method para alterá-lo.
class Animal:
def speak(self):
return "some sound"
class Cat(Animal):
def speak(self): # override
return "meow"
print(Cat().speak()) # meow
Encapsulamento 封装 esconde dados atrás de methods; um underscore inicial o marca private 私有.
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
Polimorfismo 多态 significa um nome, muitos comportamentos — o certo speak roda 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 programação
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.
Português
Um paradigm 范式 é um estilo de escrever programas. Código procedural 过程式 é uma sequência de passos e functions. Código orientado a objetos 面向对象 agrupa dados e methods em objects. Código declarativo 声明式 diz o que você quer, não como (um list comprehension ou 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)
Erros comuns
Todo method precisa de self como seu primeiro parâmetro.
__init__ configura um novo objeto e roda automaticamente quando você cria um.
Dois objects da mesma class têm attributes separados; alterar um não altera o outro.
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:
Português
Um bit 比特 é um único 0 ou 1. Binário 二进制 é o sistema numérico base-2: cada posição vale o dobro da anterior à direita (1, 2, 4, 8, …). Decimal 十进制 (base-10) são nossos números normais.
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.
Português
Compression 压缩 torna dados menores. Lossless 无损 compression mantém todos os bits, então você reconstrói o original exatamente. Lossy 有损 compression joga fora detalhes — menor mas não exato — e é usado para fotos e música.
Run-length encoding 游程编码 é um método lossless simples: armazene um run 游程 (uma repetição) como um count mais o value.
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
Erros comuns
n bits armazenam 2**n valores diferentes, de 0 até 2**n - 1.
Lossy compression joga fora detalhes e não pode ser desfeito; lossless pode ser revertido exatamente.
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.
Português
Computação 计算 significa resolver problemas com computadores: input, process, output. Good software é construído em um design cycle 设计循环 — plan, write, test, improve — repetidas muitas vezes.
Quebre um problema, construa uma parte pequena, teste-a, depois adicione mais.
Programadores trabalham em equipe e reutilizam o código uns dos outros.
16.2
A 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
Português
A Internet 互联网 es una red de redes. Los datos se dividen en paquetes 数据包 que viajan por separado y se recombinan en el otro extremo. Las reglas compartidas llamadas protocolos 协议 (como TCP/IP) hacen esto posible. Si un camino se interrumpe, los paquetes toman otra ruta: esto es redundancia 冗余, lo que proporciona tolerancia a fallos 容错.
Un mapa de la Internet: cada línea es un camino entre dos redes
Capa
Tarea
HTTP
solicitar y enviar páginas web
TCP
entrega confiable, en orden
IP
direccionamiento y enrutamiento
16.3
Cómputo paralelo y distribuido
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.
Português
El código secuencial 顺序 realiza un paso a la vez. El cómputo paralelo 并行 realiza varios pasos a la vez en muchos núcleos 核心, lo que puede proporcionar aceleración 加速. El cómputo distribuido 分布式 reparte el trabajo entre muchas computadoras, como en la nube.
No todo puede ejecutarse en paralelo: algunos pasos deben esperar un resultado anterior.
16.4
Impacto del cómputo
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.
Português
El cómputo trae tanto beneficios como perjuicios. La brecha digital 数字鸿沟 significa que no todos tienen acceso igualitario a él. El software puede transportar sesgo 偏见 proveniente de los datos con los que aprende. Respetar la propiedad intelectual 知识产权 (licencias), y proteger los datos personales 个人数据 y la privacidad 隐私 de las personas.
Erros comuns
La Internet y la World Wide Web no son lo mismo: la Web es un servicio que se ejecuta sobre la Internet.
Más núcleos de procesador ayudan solo si el trabajo puede dividirse en partes que se ejecuten al mismo tiempo.
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.
Português
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 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 use selección 选择 e iteración 迭代, y alguna entrada/salida. Cada proyecto arriba tiene exactamente esa forma: construya piezas pequeñas y luego únalas.
Erros comuns
Construya en pasos pequeños y pruebe cada parte antes de continuar; no escriba todo de una vez.
Lea toda la tarea primero, luego planifique la entrada → proceso → salida antes de codificar.
Mini-proyecto: datos → función → resultado impreso
Pick one and the site follows you — notes, papers, videos and practice all open on it. · Escolha uma e o site te seguirá — notas, provas, vídeos e prática abrirão nela.
Type to search notes, lessons, code, vocabulary and past-paper questions across every subject. · Digite para pesquisar notas, aulas, código, vocabulário e questões de provas anteriores em todas as disciplinas.