Loops in Python

If anidadoBucle While

Loops are a fundamental part of programming. They allow you to repeat a block of code multiple times without writing it over and over.

In real programs, repetition is everywhere: processing items in a list, counting, waiting for input, drawing patterns, or running animations. Loops make these tasks efficient and keep your code clean.

Python has two main loop types:

  • while loop – repeats as long as a condition is true
  • for loop – repeats over a sequence (like a list or range of numbers)

Both use indentation to define the block of code that repeats. We'll start with a general overview, then dive deeper into each type in the following lessons.

Why Loops Are Important

Without loops, simple tasks would require writing the same code many times. For example, printing numbers 1 to 100 manually would mean 100 print statements!

Loops solve this by automating repetition. They also make code more flexible – change one number and the whole behavior updates.

Common Loop Patterns

You'll use loops for:

  • Counting up or down
  • Processing every item in a collection
  • Repeating until a condition is met
  • Building patterns or tables
  • Game logic and animations

Loop Control Statements

Python provides tools to control loops:

  • break – exit the loop early
  • continue – skip to the next iteration
  • else clause – runs when the loop finishes normally (not with break)

Simple Example – Repeating a Message

Here’s the same task with both loop types.

Using while:

Using for with range:

Both produce the same output – choose based on whether you know the number of repetitions in advance.

When to Use Which Loop

while loop: Use when the number of repetitions is unknown – like waiting for user input or until a condition changes.

for loop: Use when you know how many times to repeat or are looping over a sequence (list, string, range).

Avoiding Infinite Loops

An infinite loop runs forever because the condition never becomes false. Our editor has protection, but always make sure your loop has a way to stop.

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.