Loops in Python

for and while, range(), break and continue — and when a loop is the wrong tool entirely.

5 minute read · Free · Taught properly in our Python Training in Amritsar

Python has two loops. for walks through a collection. while repeats until a condition stops being true.

for

for city in ["Amritsar", "Jalandhar", "Ludhiana"]:
    print(city)

There is no counter and no index. for takes items one at a time from anything you can iterate — a list, a string, a dictionary, a file.

When you do need numbers, use range():

for i in range(5):        # 0 1 2 3 4
    print(i)

for i in range(1, 11):    # 1 to 10
    print(i)

for i in range(0, 20, 5): # 0 5 10 15
    print(i)

range(5) stops before 5. Everybody gets this wrong once, usually in a table-printing assignment that prints one row too few.

If you need the position as well as the item, do not build a counter by hand:

for index, city in enumerate(["Amritsar", "Jalandhar"]):
    print(index, city)

while

balance = 4500
while balance > 0:
    balance -= 1500
    print(balance)

Use while when you do not know in advance how many times it will run — reading until a file ends, retrying until a connection works, asking until the user types something valid.

The classic bug is forgetting to change the thing the condition tests, so the loop never ends. If your program hangs, that is usually why. Ctrl+C stops it.

break and continue

break leaves the loop immediately. continue skips the rest of this pass and starts the next one.

for n in range(1, 21):
    if n % 3 != 0:
        continue      # not a multiple of 3, skip it
    if n > 15:
        break         # stop entirely
    print(n)          # 3 6 9 12 15

When not to use a loop

Python often has a shorter way, and reviewers expect it:

# Instead of this
squares = []
for n in range(10):
    squares.append(n * n)

# write this
squares = [n * n for n in range(10)]

That is a list comprehension. Reach for it when a loop's only job is to build a list. Keep the plain loop when there is real work inside, because a comprehension with three conditions in it is harder to read than the loop it replaced.

Stuck on this in your own code?

That is what a class is for. Sit one for free at WebPrims on Majitha Road, Amritsar — write some Python, ask the mentor why yours is not working, and decide afterwards.