Putting it all together · Juntando tudo
Putting it all together
- You now know variables, input,
if, loops, lists, functions, and dictionaries. - A real program combines these small pieces into one useful tool.
- In this lesson you build a tiny class-scores analyzer, one function at a time.
Juntando tudo
- Agora você conhece variáveis, entrada,
if, loops, listas, funções e dicionários. - Um programa real combina essas peças pequenas em uma ferramenta útil.
- Nesta aula, você constrói um analisador de notas de turma minúsculo, função por função.
The plan
- We have a list of test scores, like
[70, 90, 50, 80]. - We want three answers: the average, how many passed, and a short summary.
- We will write one small function for each job, then they work together.
O plano
- Temos uma lista de notas de prova, como
[70, 90, 50, 80]. - Queremos três respostas: a média, quantos aprovaram e um resumo curto.
- Escreveremos uma pequena função para cada trabalho, então elas funcionarão juntas.
The analyzer calls each helper · O analisador chama cada auxiliar
A big program calls small functions in turn, each returning one answer. · Um grande programa chama funções pequenas sequencialmente, cada uma retornando uma resposta.
Handy built-ins for lists
- Python gives you ready-made helpers that work on a list of numbers.
len(x)counts the items,sum(x)adds them,max(x)/min(x)find the largest / smallest.- Use them instead of writing a loop every time.
Funções embutidas úteis para listas
- Python oferece auxiliares prontos que funcionam em uma lista de números.
len(x)conta os itens,sum(x)soma-os,max(x)/min(x)encontram o maior / menor.- Use-os em vez de escrever um loop toda vez.
scores = [70, 90, 50, 80]
print(len(scores)) # 4
print(sum(scores)) # 290
print(max(scores)) # 90
print(min(scores)) # 50
A pattern you will reuse: count items that pass a test
- A very common job: loop a list, and count the items that pass some test.
- Start a counter at
0, and add1each time theifis true. - Here we count the long words; soon you will count the passing scores.
Um padrão que você reutilizará: contar itens que passam em um teste
- Um trabalho muito comum: iterar uma lista e contar os itens que passam em algum teste.
- Comece um contador em
0, e adicione1sempre que oiffor verdadeiro. - Aqui contamos as palavras longas; em breve você contará as notas aprovadas.
def how_many_long_words(words, min_length):
count = 0
for w in words:
if len(w) >= min_length:
count = count + 1
return count
print(how_many_long_words(["hi", "hello", "hey", "howdy"], 4)) # 2
Common mistakes
- Build in small pieces and test each one before adding the next.
- Read the whole task first, then plan before you code.
Erros comuns
- Construa em peças pequenas e teste cada uma antes de adicionar a próxima.
- Leia a tarefa inteira primeiro, depois planeje antes de codificar.
Now you try
- Build the analyzer in three steps:
average,count_passing, thenstats. - Each function is small. Together they turn a list of scores into real answers.
- Press Check answer after each one.
Agora você tenta
- Construa o analisador em três etapas:
average,count_passinge depoisstats. - Cada função é pequena. Juntas, elas transformam uma lista de pontuações em respostas reais.
- Pressione Verificar resposta após cada uma.
Write average(scores) that returns the average (mean) of a list of numbers: the total divided by how many. If the list is empty · vazios, return 0 (so it does not crash). Example: average([2, 4]) is 3.0. · Escreva average(scores) que retorne a média (média aritmética) de uma lista de números: o total dividido pela quantidade. Se a lista for vazia, retorne 0 (para não crashar). Exemplo: average([2, 4]) é 3.0.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write count_passing(scores, pass_mark) that returns how many scores are greater than or equal to pass_mark. Loop the list and count. Example: count_passing([40, 50, 60], 50) is 2. · Escreva count_passing(scores, pass_mark) que retorna quantas notas são maiores ou iguais a pass_mark. Percorra a lista e conte. Exemplo: count_passing([40, 50, 60], 50) é 2.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write stats(scores) (assume at least one score) that returns a dictionary with three keys: "highest", "lowest", and "average". Example: stats([70, 90, 50, 80]) returns · decrescentes {"highest": 90, "lowest": 50, "average": 72.5}. · Escreva stats(scores) (assuma pelo menos uma nota) que retorne um dicionário com três chaves: "highest", "lowest" e "average". Exemplo: stats([70, 90, 50, 80]) retorna {"highest": 90, "lowest": 50, "average": 72.5}.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write grade_counts(scores) that returns · decrescentes a dictionary counting grades: A for 80 and above, B for 60 and above, C for the rest. Always include all three keys: grade_counts([85, 72, 90, 40]) is {"A": 2, "B": 1, "C": 1}. · Escreva grade_counts(scores) que retorne um dicionário contando notas: A para 80 e acima, B para 60 e acima, C para o resto. Sempre inclua as três chaves: grade_counts([85, 72, 90, 40]) é {"A": 2, "B": 1, "C": 1}.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.