Python Loops: For and While Loops Explained
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
Overview
Loops are one of the most fundamental concepts in programming. They allow you to execute a block of code multiple times without rewriting it.
In Python, there are two primary types of loops: the "for" loop and the "while" loop.
A "for" loop iterates over a sequence (like a list, tuple, dictionary, set, or string). A "while" loop executes a set of statements as long as a condition is true.
Code Example
This example demonstrates iteration over a list using a for loop, and a simple countdown pattern using a while loop.
names = ["Alice", "Bob", "Charlie"]
print("--- For Loop ---")
for name in names:
print(f"Hello, {name}!")
print("\n--- While Loop ---")
count = 3
while count > 0:
print(f"Countdown: {count}")
count -= 1
print("Go!")--- For Loop ---
Hello, Alice!
Hello, Bob!
Hello, Charlie!
--- While Loop ---
Countdown: 3
Countdown: 2
Countdown: 1
Go!Real-world Use Cases
- Processing large datasets line by line
- Automating repetitive background tasks
- Polling for server responses until successful
Frequently Asked Questions
How do I exit a loop early?
You can use the "break" statement to immediately terminate the loop and resume execution at the next statement.
What is the "continue" statement?
"continue" skips the rest of the current iteration and moves directly back to the loop's condition evaluation.