for loop
Loops over any iterable — list, string, range, dictionary, file:
for fruit in fruits:
range()
range(5) → 0–4, range(1, 6) → 1–5, range(10, 0, -2) → 10, 8, 6, 4, 2.
Helpful functions
enumerate(items, start=1)— index and value togetherzip(names, marks)— loop over two lists in parallelreversed(),sorted()
while loop
Repeats while a condition is True. Make sure something changes, or you get an infinite loop (stop with Ctrl+C).
Loop control
break— exit the loop nowcontinue— skip to the next roundpass— do nothing (placeholder)elseon a loop — runs only if the loop finished withoutbreak
Nested loops
A loop inside a loop — e.g. rows and columns of a table.
Example
Example — Loop examples
Python
students = ["Asha", "Ravi", "Neha"]
marks = [88, 64, 91]
for i, (name, m) in enumerate(zip(students, marks), start=1):
print(f"{i}. {name}: {m}")
for n in range(1, 11):
if n % 2 == 0:
continue # skip even numbers
if n > 7:
break # stop after 7
print(n, end=" ")
print()
# while: guess game logic
secret, tries = 7, 0
for guess in [3, 9, 7]:
tries += 1
if guess == secret:
print(f"Found in {tries} tries")
break
else:
print("Not found")
count = 3
while count > 0:
print("Countdown:", count)
count -= 1
Prints a numbered list of students and marks, then 1 3 5 7, "Found in 3 tries", and a countdown 3, 2, 1.