Python loops repeat a block of code without requiring you to write the same instructions again and again. They are used to process lists, read files, validate input, create menus, calculate totals, and automate repetitive tasks.
Python has two main loop structures: for and while. This guide explains how each one works, when to choose it, and how to use range(), break, continue, else, enumerate(), zip(), nested loops, and practical patterns safely.
Review Python data types and the in operator if collections and membership are still new.
What Is a Loop?
A loop executes an indented code block repeatedly. The repetition may happen once for every item in a collection or while a condition remains true.
The official Python control flow tutorial covers loops and related statements. The range documentation defines numeric sequence behavior.
The for Loop
A for loop iterates over an iterable such as a list, tuple, string, dictionary, set, range, or file.
languages = ["Python", "JavaScript", "Go"]
for language in languages:
print(language)On each iteration, language receives the next value. The loop ends when there are no more items.
Loop Over a String
for character in "Python":
print(character)Strings are iterable, so each iteration returns one character.
Use range()
range() generates integer values lazily:
for number in range(5):
print(number)The output is 0 through 4. The stop value is excluded.
for number in range(2, 11, 2):
print(number)This starts at 2, stops before 11, and advances by 2.
Calculate a Total
prices = [19.90, 35.50, 12.00]
total = 0
for price in prices:
total += price
print(f"Total: {total:.2f}")Python also provides sum(prices), which is clearer for simple totals. Loops are useful when each item needs additional validation or transformation.
Use enumerate() for Indexes
Avoid manually updating an index variable:
tasks = ["Study loops", "Write code", "Run tests"]
for position, task in enumerate(tasks, start=1):
print(f"{position}. {task}")The enumerate guide includes files, custom start values, and combined loops.
Loop Over Dictionaries
student = {
"name": "Maya",
"course": "Python",
"active": True,
}
for key, value in student.items():
print(f"{key}: {value}")Iterating directly over a dictionary returns its keys. Use items() when you need both keys and values.
Loop Over Multiple Collections with zip()
names = ["Alex", "Sam", "Maya"]
scores = [85, 92, 88]
for name, score in zip(names, scores):
print(f"{name}: {score}")By default, zip() stops when the shortest iterable ends. Validate lengths when missing data would be a problem.
The while Loop
A while loop repeats while its condition is true:
count = 1
while count <= 5:
print(count)
count += 1The condition must eventually become false. Forgetting count += 1 would create an infinite loop.
Input Validation with while
while True:
text = input("Enter a positive integer: ")
if text.isdigit() and int(text) > 0:
number = int(text)
break
print("Invalid value. Try again.")
print(f"You entered {number}.")while True is appropriate when the stopping point depends on an event inside the loop.
Use break
break immediately exits the nearest loop:
numbers = [4, 8, 15, 16, 23, 42]
target = 15
for number in numbers:
if number == target:
print("Target found")
breakOnly the innermost loop is affected when loops are nested.
Use continue
continue skips the rest of the current iteration:
values = [10, -2, 7, -5, 3]
for value in values:
if value < 0:
continue
print(value)Use it sparingly. A clear condition around the main logic is sometimes easier to read.
The Loop else Clause
A loop’s else block runs when the loop ends normally, not when it exits through break.
numbers = [4, 8, 15, 16]
target = 23
for number in numbers:
if number == target:
print("Found")
break
else:
print("Not found")This pattern is useful for searches and validation.
Nested Loops
for row in range(1, 4):
for column in range(1, 4):
print(f"({row}, {column})")The inner loop completes for every iteration of the outer loop. Three rows multiplied by three columns produce nine iterations.
Create a Multiplication Table
for row in range(1, 6):
line = []
for column in range(1, 6):
line.append(f"{row * column:2}")
print(" ".join(line))Nested loops are useful for grids, tables, matrices, and game boards, but their work grows quickly as input sizes increase.
Loop Through a File
from pathlib import Path
file_path = Path("events.txt")
with file_path.open(encoding="utf-8") as file:
for line_number, line in enumerate(file, start=1):
cleaned = line.strip()
if cleaned:
print(line_number, cleaned)Iterating directly over the file processes one line at a time and is suitable for large text files. See the text files guide.
List Comprehensions
A simple loop that builds a list can sometimes become a comprehension:
squares = []
for number in range(1, 6):
squares.append(number ** 2)
# Equivalent concise form
squares = [number ** 2 for number in range(1, 6)]Use the regular loop when the logic requires several steps, error handling, or side effects. The list comprehensions guide explains filters and readability limits.
Modify Collections Safely
Removing items from a list while iterating over the same list can skip values:
numbers = [1, 2, 3, 4, 5, 6]
# Safer: build a new list
numbers = [number for number in numbers if number % 2 != 0]
print(numbers)When mutation is required, iterate over a copy or clearly separate reading from modification.
Practical Project: Expense Summary
expenses = [
{"category": "Food", "amount": 24.50},
{"category": "Transport", "amount": 15.00},
{"category": "Food", "amount": 32.90},
{"category": "Books", "amount": 45.00},
]
totals = {}
total_spent = 0
for expense in expenses:
category = expense["category"]
amount = expense["amount"]
total_spent += amount
totals[category] = totals.get(category, 0) + amount
print(f"Total spent: {total_spent:.2f}")
for category, amount in sorted(totals.items()):
print(f"{category}: {amount:.2f}")The project combines a list of dictionaries, accumulation, dictionary lookup, and a final reporting loop. For more sorting options, read sort() vs sorted().
Practical Project: Limited Guessing Game
import random
secret = random.randint(1, 20)
maximum_attempts = 5
for attempt in range(1, maximum_attempts + 1):
try:
guess = int(input(f"Attempt {attempt}: "))
except ValueError:
print("Enter a whole number.")
continue
if guess == secret:
print("Correct!")
break
if guess < secret:
print("Too low.")
else:
print("Too high.")
else:
print(f"No attempts left. The number was {secret}.")This combines for, continue, break, and loop else. The random module guide explains random number generation.
Avoid Infinite Loops
Before writing a while loop, answer three questions:
- What condition starts as true?
- What changes during every relevant iteration?
- What event makes the condition false or triggers
break?
When a loop never ends, interrupt it in a terminal with Ctrl+C and inspect its condition and update logic.
Common Mistakes
- Forgetting indentation.
- Expecting
range(5)to include 5. - Forgetting to update a
whilecondition. - Using
breakwhencontinuewas intended. - Modifying a list while iterating over it.
- Using manual indexes instead of
enumerate(). - Creating deeply nested loops without considering the amount of work.
- Using a comprehension for logic that is too complex to read.
Frequently Asked Questions
What is the difference between for and while?
for iterates over items. while repeats based on a condition.
Can a loop run zero times?
Yes. A for loop over an empty iterable and a while loop with an initially false condition do not execute their bodies.
Does break exit every nested loop?
No. It exits only the nearest loop. Use a function, flag, or other control structure when several levels must stop.
Is a list comprehension always faster?
It may be efficient for simple transformations, but readability and correctness should guide the choice.
Conclusion
Use for to process iterables and while when repetition depends on a changing condition. Add enumerate() for indexes, zip() for parallel collections, and break or continue only when they make the flow clearer.
The best way to learn loops is to predict each iteration before running the code. Trace variable values on paper, then compare your prediction with the output.






