agyanadda@gmail.com

Python Loops: for and while

Control Flow 1 min read Updated Dec 4, 2026 Topic 11 of 32

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 together
  • zip(names, marks) — loop over two lists in parallel
  • reversed(), 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 now
  • continue — skip to the next round
  • pass — do nothing (placeholder)
  • else on a loop — runs only if the loop finished without break

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.

Test Yourself With Exercises

Exercise 1 Multiple Choice

What does range(1, 5) produce?

Exercise 2 True / False

continue exits the loop completely.

Exercise 3 Fill in the Blank

Get index and value together with ___(items)

Frequently Asked Questions

Use for when you loop over a known collection or a fixed number of times. Use while when you repeat until something happens, such as valid input or a game ending.