We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

Python Loops: For, While, and Range Explained

Lane Wagner
Lane WagnerBoot.dev co-founder and backend engineer

Last published

Table of Contents

Loops let you run the same code over and over without rewriting it each time. Whether you need to count through numbers, process items in a list, or keep going until a condition changes, Python gives you for loops and while loops to handle it.

All the content from our Boot.dev courses are available for free here on the blog. This one is the "Loops" chapter of Learn Python for Beginners. If you want to try the far more immersive version of the course, do check it out!

How Does a For Loop Work in Python?

Let's say you want to print the numbers 0 through 9. You could write ten print statements:

print(0)
print(1)
print(2)
# ... you get the idea
print(9)

A for loop saves you all that typing — especially if you wanted to do the same thing a thousand or a million times:

for i in range(0, 10):
    print(i)

The variable i takes on each value from 0 to 9, one at a time. In plain English:

  1. Start with i equals 0

  2. If i is greater than or equal to 10, exit the loop. Otherwise:

    • Print i to the console

    • Add 1 to i

    • Go back to step 2

The numbers in range(a, b) are inclusive of a and exclusive of b, so range(0, 10) includes 0 but not 10.

How Does range() Work in Python?

The range() function actually takes up to three parameters: range(start, stop, step).

The step parameter controls how much i changes each iteration. By default it's 1, but you can change it:

for i in range(0, 10, 2):
    print(i)
# 0
# 2
# 4
# 6
# 8

You can even go backwards with a negative step:

for i in range(3, 0, -1):
    print(i)
# 3
# 2
# 1

This is useful any time you need to count down or iterate in reverse.

Why Does Whitespace Matter in Python Loops?

The body of a for loop must be indented, otherwise you'll get a SyntaxError. Every line in the body needs to be indented the same way — the convention is 4 spaces. Pressing Tab should insert 4 spaces automatically in most editors.

This is the same indentation rule that applies to if statements, functions, and every other block in Python. Whitespace matters.

How Do While Loops Work in Python?

A while loop keeps running as long as its condition is True:

while 1:
    print("1 evaluates to True")
# prints forever (infinite loop)

That example runs forever. Normally, a while loop's condition involves a comparison that eventually becomes False:

num = 0
while