Skip to main content

What are loops?

Loops let you repeat code without writing it multiple times. Instead of copying and pasting, you tell Python to repeat the code for you. Without loops:
With loops:
Both do the same thing, but the loop is much cleaner!

For loops

The for loop is the most common loop in Python. Let’s start simple:

Repeat a specific number of times

Python starts counting at 0, not 1. This is called “zero-indexing”. So range(5) gives you 0, 1, 2, 3, 4 (five numbers total).

Count from different starting points

Loop through text

You can loop through each character in a string:

Loop through a list (preview)

We’ll learn more about lists later, but here’s a preview:

While loops

A while loop continues as long as a condition is true:
Always make sure your while loop will eventually stop! If you forget to update the variable, it will run forever.

Common mistakes

Data structures

Learn about lists, dictionaries, and more