Iteration · Iteração
Repeat with iteration
- Iteration means doing the same steps again and again.
- Loops save you from writing the same line many times.
- AP CSP cares about loops because they let a little code do a lot of work.
Repita com iteração
- Iteração significa fazer os mesmos passos repetidamente.
- Loops economizam você de escrever a mesma linha muitas vezes.
- O AP CSP se importa com loops porque permitem que um pouco de código faça muito trabalho.
Count with for and range
for i in range(n):repeats the bodyntimes.range(5)gives0, 1, 2, 3, 4(it stops before 5).- The loop body is indented, like an
if.
Conte com for e range
for i in range(n):repete o corponvezes.range(5)dá0, 1, 2, 3, 4(ela para antes do 5).- O corpo do loop está indentado, como um
if.
for i in range(5):
print(i)
Build a total (accumulation)
- An accumulator is a variable that grows inside a loop.
- Start it at
0before the loop. - Add to it each pass to build a running total.
Construa um total (acumulação)
- Um acumulador é uma variável que cresce dentro de um loop.
- Inicie-o em
0antes do loop. - Adicione a ele a cada passagem para construir um total acumulado.
total = 0
for n in range(1, 6):
total = total + n
print(total)
Loop until a condition with while
- A
whileloop repeats as long as its condition isTrue. - Something inside must move toward making it
False. - Use it when you do not know the count in advance.
Loop até uma condição com while
- Um loop
whilerepete enquanto sua condição forTrue. - Algo dentro deve se mover para torná-la
False. - Use quando você não sabe a contagem com antecedência.
count = 3
while count > 0:
print(count)
count = count - 1
Loop over a list (for-each)
for item in mylist:visits each item in turn.- The loop variable holds one item per pass.
- This is the clean way to process every value.
Iteração sobre uma lista (for-each)
for item in mylist:visita cada item em sequência.- A variável de loop armazena um item por passagem.
- Esta é a forma mais limpa de processar todos os valores.
scores = [10, 20, 30]
for s in scores:
print(s)
In AP CSP pseudocode
- CB has three loop shapes that match Python loops.
REPEAT n TIMES= a fixed count;REPEAT UNTIL(cond)= loop until true.FOR EACH x IN list= a for-each loop.DISPLAY= print,←==,MOD=%.
Em pseudocódigo AP CSP
- CB tem três formatos de loop que correspondem aos loops do Python.
REPEAT n TIMES= uma contagem fixa;REPEAT UNTIL(cond)= loop até que seja verdadeiro.FOR EACH x IN list= um loop for-each.DISPLAY= print,←==,MOD=%.
REPEAT 5 TIMES
{
DISPLAY "hi"
}
count ← 3
REPEAT UNTIL (count = 0)
{
DISPLAY count
count ← count - 1
}
FOR EACH s IN scores
{
DISPLAY s
}
Common mistakes
range(n)runs0ton - 1.- Change the condition inside a
while, or it never stops.
Erros comuns
range(n)executa de0an - 1.- Mude a condição dentro de um
while, ou ele nunca para.
Now you try
- Use a loop in each task.
- Press Check answer to test your code.
Agora você tenta
- Use um loop em cada tarefa.
- Clique em Check answer para testar seu código.
Iteration repeats the body · Iteração repete o corpo
A loop repeats; a counter and a total change each pass. · Um loop repete; um contador e um total mudam a cada passagem.
Use a for loop with range(...) to add the whole numbers 1 through 10. Store the result in total. (It should be 55.) · Use um loop for com range(...) para somar os números inteiros 1 através de 10. Armazene o resultado em total. (Deve ser 55.)
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Use a while loop to print the numbers 5, 4, 3, 2, 1, each on its own line, then print Go. Start from n = 5. · Use um loop while para imprimir os números 5, 4, 3, 2, 1, cada um em sua própria linha, depois imprima Go. Comece de n = 5.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
nums is [3, 6, 7, 8, 10, 11]. Loop over it with a for-each loop and count how many values are even (use % 2 == 0). Store the count in evens. (It should be 3.) · nums é [3, 6, 7, 8, 10, 11]. Faça o loop sobre ele com um loop for-each e conte quantos valores são pares (use % 2 == 0). Armazene a contagem em evens. (Deve ser 3.)
Click Run to see the output here. · Clique em Executar para ver a saída aqui.