For and While Loops
Iterating with for loops over sequences and range(), and repeating with while.
2 min read
Python has two loop constructs: for, which iterates over a sequence of items, and while, which repeats as long as a condition holds. Most everyday iteration in Python reaches for for.
For loops iterate over sequences
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)This is meaningfully different from a C-style for (int i = 0; i < len; i++) loop — there's no index variable to manage, no off-by-one risk. You're asking directly for each item in the sequence, one at a time.
Iterating over a string works the same way, giving you one character per pass:
for letter in "abc":
print(letter)range() for counting loops
When you do need to loop a specific number of times, range() generates a sequence of numbers on demand:
for i in range(5):
print(i) # 0, 1, 2, 3, 4range(5) counts from 0 up to (but not including) 5. You can also give it a start and step:
for i in range(2, 10, 2):
print(i) # 2, 4, 6, 8Getting both index and value with enumerate()
Needing the index while looping over a list is common enough that Python has a built-in for it:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")This is preferred over manually tracking an index with range(len(fruits)) — it's shorter and impossible to get the bounds wrong on.
While loops repeat on a condition
count = 0
while count < 5:
print(count)
count += 1A while loop checks its condition before every pass and keeps going as long as it's True. Forgetting to update the variable the condition depends on (here, count += 1) produces an infinite loop — one of the most common beginner bugs, and a good first thing to check when a program hangs.
while True: combined with a break (covered in the next lesson) is a common pattern for loops that should run until some event happens rather than a fixed number of times:
while True:
answer = input("Type 'quit' to stop: ")
if answer == "quit":
breakChoosing between them
Default to for whenever you're iterating over a known collection or a fixed range — it's shorter and can't accidentally loop forever. Reach for while when the number of iterations isn't known ahead of time and depends on some condition changing during the loop, like waiting for user input or polling until a value is ready.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.