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:
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:
names = ["Ana", "Ravi", "Kai"]scores = [82, 95, 68]for i, name in enumerate(names): # index + itemprint(i, name) # 0 Ana, 1 Ravi, 2 Kaifor name, score in zip(names, scores): # two lists togetherprint(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:
n = 5while n > 0:print(n)n -= 1 # MUST change the condition, or it loops forever# A common pattern: loop until valid inputwhile 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 n in numbers:if n < 0:print("found a negative")breakelse:print("all numbers were non-negative") # runs only if no break
Key takeaways
- 01for iterates over a sequence; while repeats while a condition stays true.
- 02Loop over items directly; use enumerate for index+item and zip for parallel sequences.
- 03A while loop must change its condition inside the body or it runs forever.
- 04Use while True + break for "repeat until valid input" patterns.
- 05A loop's else runs only if the loop finished without a break.
