While loops · Laços While
Loop while a condition is true
- A
whileloop repeats as long as its condition is true. - It checks the condition before each pass.
- Use it when you do not know the number of repeats in advance.
Loop enquanto uma condição é verdadeira
- Um loop
whilerepete enquanto sua condição for verdadeira. - Ele verifica a condição antes de cada passagem.
- Use-o quando não souber o número de repetições com antecedência.
Always change the condition
- Something inside the loop must move toward making the condition false.
- If it never becomes false, the loop runs forever (an infinite loop).
- Press Stop if a loop ever gets stuck.
Sempre altere a condição
- Algo dentro do loop deve mudar para tornar a condição falsa.
- Se nunca ficar falso, o loop roda para sempre (um loop infinito).
- Pressione Parar se um loop travar.
count = 3
while count > 0:
print(count)
count = count - 1
break and continue
breakstops the loop right away.continueskips the rest of this pass and goes to the next one.while True:loops forever until abreakends it.
break e continue
breakpara o loop imediatamente.continueignora o resto desta passagem e vai para a próxima.while True:roda para sempre até umbreakterminá-lo.
n = 0
while True:
n = n + 1
if n == 4:
break
print(n)
Checking before or after
- A
whileloop checks first, so it may run zero times. - A "repeat until" loop checks after, so it always runs at least once.
- Python has no
repeat; usewhile True:with abreakat the end.
Verificando antes ou depois
- Um loop
whileverifica primeiro, então pode rodar zero vezes. - Um loop "repita até" verifica depois, então sempre roda pelo menos uma vez.
- Python não tem
repeat; usewhile True:com umbreakno final.
In Cambridge pseudocode
whileis the pre-condition loop;REPEAT … UNTILis the post-condition loop.
Em pseudocódigo do Cambridge
whileé o loop de pré-condição;REPEAT … UNTILé o loop de pós-condição.
Count ← 3
WHILE Count > 0
OUTPUT Count
Count ← Count - 1
ENDWHILE
REPEAT
OUTPUT Count
Count ← Count + 1
UNTIL Count = 3
Common mistakes
- Change something inside the loop so the condition can become false, or it runs forever.
- A
whilechecks its condition first, so it may run zero times.
Erros comuns
- Altere algo dentro do loop para que a condição possa ficar falsa, ou ele roda para sempre.
- Um
whileverifica sua condição primeiro, então pode rodar zero vezes.
Now you try
- Make sure your condition will eventually become false.
- Stuck on the loop? Do the short drill Finish the countdown first. It is one missing line.
- Press Check answer to test your code.
Agora você tenta
- Tenha certeza de que sua condição eventualmente ficará falsa.
- Travou no loop? Faça primeiro o drill curto Terminar a contagem regressiva. Falta apenas uma linha.
- Clique em Check answer para testar seu código.
A while loop builds up a value · Um laço while constrói um valor
A while loop repeats until its condition is false. · Um laço while repete até que sua condição seja falsa.
Use a while loop to count down. Each turn, print the value of count, then make count one smaller. Stop when it reaches 0, so the output is 5, 4, 3, 2, 1 — one per line. · Use um laço while para contar regressivamente. A cada volta, imprima o valor de count, depois faça count ser uma unidade menor. Pare quando chegar em 0, para que a saída seja 5, 4, 3, 2, 1 — um por linha.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Use a while loop to add up the numbers 1 to · até 10. Store the total in total (the answer is 55). · Use um laço while para somar os números de 1 a 10. Armazene o total em total (a resposta é 55).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Start · Iniciar n at 1 and add 1 each pass. The loop stops too soon: it ends while n is still 1. Change the condition so it keeps going while n * n is at most 50. When it stops, n is the first whole number whose square is over 50. · Comece n em 1 e adicione 1 a cada passagem. O laço para muito cedo: termina enquanto n ainda é 1. Mude a condição para continuar enquanto n * n for no máximo 50. Quando parar, n é o primeiro número inteiro cujo quadrado é maior que 50.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Same answer, with break. n starts at 1 inside while True:. The if is already inside the loop and n grows after · depois it. Change the condition so you break when n * n is greater than 50. Leave the answer in n (it is 8). Do not add 1 before the test — that makes the answer 9. · Mesma resposta, com break. n começa em 1 dentro de while True:. O if já está dentro do loop e n cresce depois dele. Altere a condição para que você break quando n * n for maior que 50. Deixe a resposta em n (é 8). Não adicione 1 antes do teste — isso faz a resposta ser 9.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Start with n = 1 and · e steps = 0. While n is smaller than 1000, double n and add 1 to · até steps. When the loop ends, n is 1024. How many doublings did it take? Leave the answer in steps. · Comece com n = 1 e steps = 0. Enquanto n for menor que 1000, dobre n e adicione 1 a steps. Quando o laço terminar, n será 1024. Quantos dobramentos foram necessários? Deixe a resposta em steps.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.