Skip to main content
Albero Academy

for & while Loops

Repeat work with for and while loops and iterate over collections the Pythonic way.

Flow Control12 min

Loops repeat a block of code, so you don't write the same thing over and over. Python has two: for loops over the items of a sequence, and while repeats as long as a condition stays true. Almost all real programs are loops around some decision.

The for loop

A for loop walks through each item of a collection. The Pythonic style iterates over the items themselves, not over index numbers:

iterating directly
for name in ["Ana", "Ravi", "Kai"]:
print(f"Hello, {name}")
# Works on any iterable: strings, ranges, dict keys…
for char in "abc":
print(char)
for key in {"a": 1, "b": 2}:
print(key) # a, b

enumerate & zip

Two built-ins make loops cleaner. enumerate gives the index alongside the item; zip walks two sequences in parallel:

index and parallel iteration
names = ["Ana", "Ravi", "Kai"]
scores = [82, 95, 68]
for i, name in enumerate(names): # index + item
print(i, name) # 0 Ana, 1 Ravi, 2 Kai
for name, score in zip(names, scores): # two lists together
print(f"{name}: {score}")

The while loop

A while loop repeats as long as its condition is true — use it when you don't know the number of iterations in advance:

repeat until a condition changes
n = 5
while n > 0:
print(n)
n -= 1 # MUST change the condition, or it loops forever
# A common pattern: loop until valid input
while True:
answer = input("Continue? (y/n) ")
if answer in ("y", "n"):
break # exit once we have a valid answer

Loop else (bonus)

A loop can have an else that runs only if the loop finished without hitting break — handy for search loops:

for…else
for n in numbers:
if n < 0:
print("found a negative")
break
else:
print("all numbers were non-negative") # runs only if no break

Key takeaways

  1. 01for iterates over a sequence; while repeats while a condition stays true.
  2. 02Loop over items directly; use enumerate for index+item and zip for parallel sequences.
  3. 03A while loop must change its condition inside the body or it runs forever.
  4. 04Use while True + break for "repeat until valid input" patterns.
  5. 05A loop's else runs only if the loop finished without a break.

Finished this chapter?

Mark it complete to track your progress through Python.