Control Flow II: Loops & Iteration

লুপ — while, for, break, continue

Read: ~28 min Intermediate 5 practice problems Live code runner

1. Why Loops Matter

A computer's real superpower is repetition — doing the same operation millions of times without ever getting tired or bored. Loops are the tool that unlocks that power. Python has two loop constructs: while (repeat as long as a condition is true) and for (iterate over a sequence). Python's for is more powerful than in most languages — it works directly over any iterable.

কম্পিউটারের আসল শক্তি হলো একই কাজ কোটি কোটি বার করার ক্ষমতা — ক্লান্ত না হয়ে, বিরক্ত না হয়ে। লুপ সেই শক্তিকে আমাদের হাতে এনে দেয়। Python-এ দুটি লুপ: while (শর্ত সত্য থাকা পর্যন্ত চলবে) এবং for (যেকোনো sequence-এর উপর চলবে)। Python-এর for বেশিরভাগ ভাষার চেয়ে শক্তিশালী — এটি সরাসরি যেকোনো iterable-এর উপর কাজ করে।

2. The while Loop

while repeats its body as long as the condition is true. It is the right choice when you don't know how many iterations you need in advance — e.g., "keep asking the user until they type 'q'".

countdown.py
n = 5
while n > 0:
    print(n, end=" ")
    n -= 1
print("\nBlast off! 🚀")
Invariants — Every good while loop has a property that stays true at the top of every iteration. Write it as a comment: # invariant: n ≥ 0 and we printed (5-n) numbers. This discipline eliminates most off-by-one bugs.

3. The for Loop — Python's Workhorse

Python's for does not iterate over indices like C's. It iterates over the items of an iterable directly. This makes it cleaner and less error-prone.

for_demo.py
fruits = ["mango", "jackfruit", "lychee"]

for fruit in fruits:
    print(f"I love {fruit}")

# Iterate over a string — each char is an item
for ch in "Dhaka":
    print(ch, end=" ")
print()

# Iterate over a dict — gets keys by default
info = {"name": "Ayesha", "city": "Khulna"}
for key in info:
    print(key, "→", info[key])

4. range(), enumerate(), zip()

Three iteration helpers you will use every day.

helpers.py
# range(stop) / range(start, stop) / range(start, stop, step)
print(list(range(5)))
print(list(range(1, 10, 2)))

# enumerate — index + value
names = ["Asif", "Mou", "Tanvir"]
for i, n in enumerate(names, start=1):
    print(f"{i}. {n}")

# zip — walk two sequences together
prices = [120, 80, 45]
for n, p in zip(names, prices):
    print(f"{n}: {p} Tk")

5. break, continue, and the Loop's else

break exits the loop immediately. continue skips to the next iteration. Both loops support an else clause that runs only if the loop finished without a break — useful for "search and not found" patterns.

break_continue.py
# Find first number divisible by 7
for n in [3, 8, 14, 22]:
    if n % 7 == 0:
        print(f"Found: {n}")
        break
else:
    print("No multiple of 7 found")

# Skip even numbers
for n in range(1, 8):
    if n % 2 == 0:
        continue
    print(n, end=" ")
print()

6. Nested Loops

Loops can contain loops. A classic use: producing 2-D patterns or pair-wise operations.

nested.py
# Multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i*j:3}", end=" ")
    print()

# Right triangle pattern
for i in range(5):
    print("*" * (i + 1))

7. Vocabulary (শব্দভাণ্ডার)

TermMeaningবাংলায়
IterableAnything you can iterate over with for.for দিয়ে iterate করা যায় এমন যেকোনো কিছু।
IterationOne pass through the loop body.লুপের একটি ধাপ।
InvariantA property that stays true throughout the loop.প্রতিটি iteration-এ যে শর্ত সত্য থাকে।
range(n)Produces 0, 1, ..., n-1 lazily.0, 1, ..., n-1 lazy ভাবে তৈরি করে।
enumerate(it)Pairs each item with its index.প্রতিটি item-কে তার index-সহ দেয়।
zip(a, b)Walks two iterables in lock-step.দুটি iterable-কে একসাথে iterate করে।

8. Practice Problems

  1. Print the sum of the first 100 natural numbers using a for loop.
    for loop দিয়ে প্রথম ১০০টি natural number-এর যোগফল প্রিন্ট করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans1.py
    total = 0
    for i in range(1, 101):
        total += i
    print(total)
  2. Write a program that prints only odd numbers from 1 to 20 using continue.
    continue ব্যবহার করে ১ থেকে ২০-এর মধ্যে শুধু বিজোড় সংখ্যাগুলো প্রিন্ট করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans2.py
    for n in range(1, 21):
        if n % 2 == 0:
            continue
        print(n, end=" ")
    print()
  3. Given a list of numbers, find the first negative one and report its index. If none, say so.
    একটি list থেকে প্রথম negative সংখ্যার index বের করুন। না পেলে সেটি জানান।
    ✨ Show Answer (উত্তর দেখুন)
    ans3.py
    nums = [3, 7, -2, 8, -5]
    for i, v in enumerate(nums):
        if v < 0:
            print(f"First negative at index {i} → {v}")
            break
    else:
        print("No negative numbers")
  4. Using zip, print pairs (name, age) from two parallel lists.
    zip ব্যবহার করে দুটি parallel list থেকে (name, age) জোড়া প্রিন্ট করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans4.py
    names = ["Asif", "Mou", "Tanvir"]
    ages  = [21, 22, 20]
    for n, a in zip(names, ages):
        print(f"{n} is {a}")
  5. Print a 5-row triangle of stars (first row 1 star, fifth row 5 stars).
    ৫-সারি star triangle প্রিন্ট করুন (প্রথম সারিতে ১টি, পঞ্চম সারিতে ৫টি)।
    ✨ Show Answer (উত্তর দেখুন)
    ans5.py
    for i in range(1, 6):
        print("*" * i)

Summary — Module 10

while repeats based on a condition; for iterates over an iterable. Use range, enumerate, and zip to make for loops elegant. break exits early; continue skips to the next iteration; the loop's else runs only when the loop finishes normally. Writing invariants for your loops is the single biggest bug-prevention habit you can build.

while শর্তভিত্তিক পুনরাবৃত্তি; for iterable-এর উপর iteration। range, enumerate, zip দিয়ে for-কে elegant করুন। break দ্রুত বের হয়, continue পরবর্তী iteration-এ চলে যায়। loop-এর invariant লেখার অভ্যাস অনেক বাগ থেকে বাঁচাবে।

Next Module → Functions — def, arguments, *args, **kwargs।