Loops

A loop runs the same block of code over and over so you don't have to type it out by hand. Python gives you two forms: for, for stepping through a known sequence, and while, for repeating until a condition changes.

for: stepping through a sequence

A for loop walks through a list (or any other sequence) one item at a time, no manual indexing required:

>>> greeting each guest
guests = ["Amir", "Beatriz", "Chen"]
for name in guests:
    print("Welcome, " + name + "!")
Output
Welcome, Amir!
Welcome, Beatriz!
Welcome, Chen!

range(): looping a fixed number of times

When you want to repeat something a set number of times rather than loop over existing data, range() generates the sequence of numbers to loop over:

>>> counting up
for i in range(5):
    print("Lap", i)
Output
Lap 0
Lap 1
Lap 2
Lap 3
Lap 4

range(5) counts from 0 up to, but not including, 5 — five numbers in total. range(2, 8) would start at 2 instead, and range(0, 10, 2) adds a step, counting by twos.

while: repeating until a condition changes

A while loop keeps running as long as its condition stays true — useful when you don't know in advance how many times you'll need to repeat:

>>> a countdown
count = 3
while count > 0:
    print(count)
    count -= 1
print("Liftoff!")
Output
3
2
1
Liftoff!

break and continue

break exits a loop immediately; continue skips the rest of the current pass and moves on to the next one:

>>> searching a list
numbers = [4, 9, 15, 22, 30]
for n in numbers:
    if n % 2 != 0:
        continue
    print(n, "is even")
    if n == 22:
        break
Output
4 is even
22 is even

9 and 15 are odd, so continue skips them before the print line ever runs. 4 and 22 are even and get printed — and once 22 prints, break stops the loop before 30 is ever looked at.

Note: unlike a for loop over a fixed list, a while loop's condition has to actually change somewhere inside the loop body, or it never ends. Forgetting to update count in the countdown example above would leave the loop spinning forever — this is the single most common bug in beginner Python loops.