Mastering for and while Loops in Python (Guide & Examples)
Learn how to iterate through data structures cleanly, combine items and indices with enumerate, and master loop control flow.
Concepts & Theory
In Python, the `for` statement is a `for-each` construct: it iterates over items of any sequence or iterable directly without requiring manual counters.
The `range(start, stop, step)` function generates numbers lazily without allocating large lists in memory.
Use `enumerate(iterable)` whenever you need both the index and value, avoiding the unidiomatic `range(len(...))` pattern.
Code Example
Run in Playground# 1. Parcourir avec enumerate (index + élément)
langages = ["Python", "JavaScript", "Rust", "C++"]
for index, nom in enumerate(langages, start=1):
print(f"#{index} : {nom}")
# 2. Boucle while avec condition d'arrêt
compteur = 3
while compteur > 0:
print(f"Décollage dans {compteur}s...")
compteur -= 1
# 3. La clause for ... else (s'exécute si aucun break n'a eu lieu)
for val in [2, 4, 6]:
if val % 2 != 0:
print("Impair trouvé !")
break
else:
print("Tous les éléments sont pairs.")Common Pitfalls & Mistakes
✗ Using range(len(list)) instead of enumerate()
for i in range(len(items)):
print(i, items[i])for i, item in enumerate(items):
print(i, item)`enumerate` is more Pythonic, cleaner to read, and avoids out-of-bounds indexing bugs.
Frequently Asked Questions
What does the else clause do on a Python loop?▾
The `else` block executes only if the loop terminates normally without being interrupted by a `break` statement.
Master Python with interactive exercises
Complete hands-on code challenges in your browser with real-time feedback and progressive hints.
