While Loop in Python

BuclesBucle For

The while loop is a powerful tool for repeating code as long as a condition remains true. It's ideal when you don't know exactly how many times the loop needs to run – for example, waiting for user input or processing data until a certain goal is reached.

The loop checks the condition before each iteration. If it's true, the code block runs. If false, the loop stops.

Always make sure the condition will eventually become false – otherwise you get an infinite loop!

Basic While Loop Syntax

The structure is simple: while (condition): followed by an indented block.

You usually update a variable inside the loop to make the condition false eventually.

Without count += 1, the loop would run forever (infinite loop).

Counting Down

While loops are great for countdowns.

Infinite Loops – How to Avoid Them

An infinite loop runs forever because the condition never becomes false. Our editor has protection (timeout and iteration limit), but in real programs it can freeze everything.

Common causes: forgetting to update the condition variable, or wrong condition.

Loop Control Statements

break – Exit the Loop

break immediately stops the loop, even if the condition is still true.

continue – Skip to Next Iteration

continue skips the rest of the current iteration and goes to the next one.

else Clause

The else block runs when the loop finishes normally (condition becomes false) – but not if break was used.

Do-While Pattern (Simulation)

Python doesn't have a built-in do-while loop (run at least once before checking condition), but you can simulate it with while True and break.

Real-World Examples

Example 1: Password check with limited attempts

Example 2: Simple game loop

Quick Quiz

Hemos revisado y comprobado los materiales, pero aún pueden existir errores. El contenido se ofrece únicamente con fines educativos, así que úsalo bajo tu propia responsabilidad y verifica con otras fuentes si es necesario.

✨ Pregunta a Lara — tu compañera de estudio con IA

Desbloquea soporte de aprendizaje personalizado. Lara puede explicar lecciones, resumir temas y responder tus preguntas — disponible desde el plan Go y superiores.


Lara te ayuda a aprender más rápido — exclusivo para los miembros ReadyTools Go, Plus y Max.

Sigue Tu Progreso 🚀

Aprende más fácilmente siguiendo tu progreso completamente gratis.