While loops · Bucles 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.
Bucle while mientras una condición sea verdadera
- Un bucle
whilese repite mientras su condición sea verdadera. - Verifica la condición antes de cada iteración.
- Úsalo cuando no sepas de antemano cuántas veces se repetirá.
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.
Cambia siempre la condición
- Algo dentro del bucle debe tender a que la condición se vuelva falsa.
- Si nunca se vuelve falsa, el bucle se ejecuta indefinidamente (un bucle infinito).
- Presiona Stop si un bucle queda atascado.
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 y continue
breakdetiene el bucle inmediatamente.continueomite el resto de esta iteración y pasa a la siguiente.- Los bucles
while True:se ejecutan indefinidamente hasta que unbreaklos termine.
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.
Verificar antes o después
- Un bucle
whileverifica primero, por lo que puede ejecutarse cero veces. - Un bucle "repetir hasta" verifica después, por lo que siempre se ejecuta al menos una vez.
- Python no tiene
repeat; usawhile True:con unbreakal final.
In Cambridge pseudocode
whileis the pre-condition loop;REPEAT … UNTILis the post-condition loop.
En pseudocódigo de Cambridge
whilees el bucle de precondición;REPEAT … UNTILes el bucle de postcondición.
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.
Errores comunes
- Cambia algo dentro del bucle para que la condición pueda volverse falsa, o se ejecutará indefinidamente.
- Un
whileverifica su condición primero, por lo que puede ejecutarse cero veces.
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.
Ahora tú intentas
- Asegúrate de que tu condición llegará a ser falsa eventualmente.
- ¿Atascado en el bucle? Realiza primero el breve ejercicio Finish the countdown. Falta solo una línea.
- Presiona Check answer para probar tu código.
A while loop builds up a value · Un bucle while construye un valor
A while loop repeats until its condition is false. · Un bucle while se repite hasta que su condición sea 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. · Usa un bucle while para contar hacia atrás. En cada vuelta, imprime el valor de count, luego haz que count sea uno menor. Detente cuando llegue a 0, para que la salida sea 5, 4, 3, 2, 1 —uno por línea.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Use a while loop to add up the numbers 1 to · hasta 10. Store the total in total (the answer is 55). · Usa un bucle while para sumar los números del 1 al 10. Almacena el total en total (la respuesta es 55).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Start · Inicio 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. · Inicia n en 1 y suma 1 en cada pasada. El bucle termina demasiado pronto: finaliza mientras n aún es 1. Cambia la condición para que continúe mientras n * n sea como máximo 50. Cuando termine, n será el primer número entero cuyo cuadrado supere los 50.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Same answer, with break. n starts at 1 inside while True:. The if is already inside the loop and n grows after · después 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. · Misma respuesta, con break. n comienza en 1 dentro de while True:. El if ya está dentro del bucle y n crece después de él. Cambia la condición para que hagas break cuando n * n sea mayor que 50. Deja la respuesta en n (es 8). No sumes 1 antes de la prueba — eso haría que la respuesta fuera 9.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Start with n = 1 and · y steps = 0. While n is smaller than 1000, double n and add 1 to · hasta steps. When the loop ends, n is 1024. How many doublings did it take? Leave the answer in steps. · Comienza con n = 1 y steps = 0. Mientras n sea menor que 1000, duplica n y suma 1 a steps. Cuando el bucle termine, n será 1024. ¿Cuántas duplicaciones tomó? Deja la respuesta en steps.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.