Loops (for/while) in Python
Loops let a program repeat a block of code multiple times. Python provides two kinds of loops: the for loop, used to iterate over a sequence of items, and the while loop, used to repeat while a condition stays True.
The for Loop
A for loop iterates directly over the items of a sequence, such as a list, tuple, string, or set, running the indented block once per item.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# apple
# banana
# cherry
Using range() for Counted Loops
The range() built-in generates a sequence of numbers and is the standard way to run a loop a fixed number of times. It accepts one, two, or three arguments.
| Form | Meaning |
|---|---|
range(stop) | Counts from 0 up to (but not including) stop. |
range(start, stop) | Counts from start up to (but not including) stop. |
range(start, stop, step) | Counts from start to stop, increasing by step each time. |
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 6): # 2, 3, 4, 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
The while Loop
A while loop repeats its block for as long as its condition remains True. The condition is checked before every iteration, so care must be taken to update something inside the loop, or it will run forever.
count = 1
while count <= 5:
print(count)
count = count + 1
# 1, 2, 3, 4, 5
break and continue
The break statement exits a loop immediately, and the continue statement skips the rest of the current iteration and moves to the next one.
for number in range(1, 10):
if number == 5:
break # stop the loop entirely once we hit 5
print(number)
# 1, 2, 3, 4
for number in range(1, 6):
if number % 2 == 0:
continue # skip even numbers
print(number)
# 1, 3, 5
The else Clause on Loops
Python allows an else block after a for or while loop. This is a distinctly Python feature that often surprises developers coming from other languages. The else block runs only if the loop finished all its iterations without hitting a break. If the loop is stopped early with break, the else block is skipped.
# searching for a number - else runs because break never happens
numbers = [2, 4, 6, 8]
for n in numbers:
if n == 5:
print("Found 5")
break
else:
print("5 was not found in the list") # this runs
# searching for a number that IS present - else is skipped
numbers = [2, 4, 5, 8]
for n in numbers:
if n == 5:
print("Found 5") # this runs
break
else:
print("5 was not found in the list") # skipped, because break happened
Note: A helpful way to remember this: the loop's else runs when the loop completes normally, "else" no break occurred.
enumerate() for Index and Value
When you need both the position and the value while looping over a sequence, enumerate() is cleaner than manually tracking a counter variable.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
# 0 apple
# 1 banana
# 2 cherry
Nested Loops
A loop can be placed inside another loop. The inner loop completes all of its iterations for every single iteration of the outer loop.
for row in range(1, 4):
for col in range(1, 3):
print(f"row {row}, col {col}")
# row 1, col 1
# row 1, col 2
# row 2, col 1
# row 2, col 2
# row 3, col 1
# row 3, col 2