Loops (for & while)
Learn how to repeat actions in Python using for loops, while loops, range(), nested loops, and the lesser-known loop else clause.
Introduction
Loops let a program repeat an action multiple times without writing the same code over and over. Python provides two main types of loops: the for loop, which repeats a fixed number of times or over a collection, and the while loop, which repeats as long as a condition stays True.
Loops are essential for tasks like processing every item in a list, repeating a calculation until a target is reached, or running a menu until the user chooses to quit.
- How to write a for loop over ranges and sequences.
- How the range() function controls start, stop, and step.
- How to write and control a while loop.
- How to nest loops inside one another.
- The special loop else clause and how it differs from other languages.
- A quick preview of enumerate() for index+value iteration.
The for Loop
A for loop iterates over the items of a sequence — such as a list, string, or range — running the loop body once for each item.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)apple
banana
cherryfor letter in "Hi!":
print(letter)H
i
!The range() Function
The range() function generates a sequence of numbers and is most often used with for loops to repeat an action a specific number of times. It accepts up to three arguments: start, stop, and step.
| Call | Produces | Notes |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | Starts at 0 by default; stop value is excluded. |
| range(2, 6) | 2, 3, 4, 5 | Custom start, stop excluded. |
| range(0, 10, 2) | 0, 2, 4, 6, 8 | Custom start, stop, and step. |
| range(5, 0, -1) | 5, 4, 3, 2, 1 | Negative step counts downward. |
for i in range(5):
print(i, end=" ")
print()
for i in range(2, 10, 2):
print(i, end=" ")
print()
for i in range(5, 0, -1):
print(i, end=" ")
print()0 1 2 3 4
2 4 6 8
5 4 3 2 1 range(5) produces 0 through 4, not 0 through 5. The stop value is never included in the sequence — this trips up almost every beginner at least once.
The while Loop
A while loop repeats its body as long as its condition remains True. It is useful when you do not know in advance exactly how many times you need to repeat.
count = 1
while count <= 5:
print("Count:", count)
count += 1Count: 1
Count: 2
Count: 3
Count: 4
Count: 5If the condition in a while loop never becomes False (for example, if you forget to update count), the loop will run forever. Always make sure something inside the loop moves it toward ending.
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 — this is commonly used for grids, tables, and multiplication charts.
for row in range(1, 4):
for col in range(1, 4):
print(f"({row},{col})", end=" ")
print()(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3) The Loop else Clause
Python has a feature that surprises many programmers coming from other languages: both for and while loops can have an else clause. The else block runs automatically if the loop finishes normally — that is, without being stopped early by a break statement.
numbers = [2, 4, 6, 8]
for n in numbers:
if n % 2 != 0:
print("Found an odd number!")
break
else:
print("All numbers are even.")All numbers are even.numbers = [2, 4, 5, 8]
for n in numbers:
if n % 2 != 0:
print("Found an odd number!")
break
else:
print("All numbers are even.")Found an odd number!Think of it as "else = no break". The else block runs only when the loop completes every iteration without hitting a break statement. This is unique to Python — most other languages have no equivalent.
A Preview of enumerate()
A very common need is looping over a list while also tracking each item's position (index). The enumerate() function does this in a single, clean step — you will explore it in more depth in a later lesson.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)0 apple
1 banana
2 cherryCommon Mistakes
- Forgetting that range(stop) excludes the stop value.
- Writing a while loop whose condition never becomes False, causing an infinite loop.
- Confusing the loop else clause with a regular if/else — it triggers based on break, not on a condition.
- Modifying a list while iterating over it directly, which can skip items unexpectedly.
- Using an unnecessary index variable with range(len(my_list)) when enumerate() or direct iteration would be clearer.
Best Practices
- Prefer "for item in collection" over manual indexing whenever you do not strictly need the index.
- Use range() with explicit start/stop/step values for clarity rather than relying only on defaults.
- Always ensure a while loop's condition can eventually become False.
- Use the loop else clause when you need to detect "the loop finished without finding/breaking on anything".
- Keep nested loops shallow — more than two or three levels usually signals the logic should be refactored.
Frequently Asked Questions
What is the difference between for and while loops?
A for loop is best when iterating over a known sequence or a fixed number of times. A while loop is best when the number of repetitions depends on a condition that changes during execution.
Does range() include the stop value?
No. range(start, stop) always excludes the stop value — range(1, 5) produces 1, 2, 3, 4.
When does the loop else clause NOT run?
It does not run if the loop is exited early using a break statement. It runs in every other case, including when the loop body never executes at all (an empty sequence).
Can I use break and continue in both for and while loops?
Yes, both work identically in either loop type. You will explore break, continue, and pass in detail in the next lesson.
Is enumerate() required to get an index while looping?
No, but it is the cleanest way. Without it, you would need something clunkier like range(len(my_list)) combined with manual indexing.
Key Takeaways
- for loops iterate over sequences; while loops repeat based on a condition.
- range(start, stop, step) generates numeric sequences and always excludes the stop value.
- Loops can be nested, with the inner loop completing fully for each outer iteration.
- The loop else clause runs only if the loop finishes without hitting a break — a distinctly Python feature.
- enumerate() provides both index and value while looping, and will be covered in more depth later.
Summary
Loops are the backbone of repetition in Python. The for loop is ideal for iterating over known sequences, while the while loop handles repetition based on a changing condition, and the loop else clause offers a uniquely Python way to detect an uninterrupted loop.
Next, you will learn how to fine-tune loop behavior using break, continue, and pass.
- You can write for loops over sequences and ranges.
- You understand range() and its start/stop/step arguments.
- You can write while loops and avoid infinite loops.
- You understand the loop else clause and got a preview of enumerate().
- You are ready to learn break, continue, and pass.