CHAPTER 7 · CONTROL FLOW

Python Loops

Loops repeated work ko automate karte hain. Is chapter me for, while, range(), break, continue, loop else, nested loops, enumerate(), zip() aur practical loop patterns samjhenge.

English + Hinglish55 min readOnline practice included

What is a loop?

A loop repeats a block of code while following a defined iteration rule or condition.

repeat.pyPython
for number in range(1, 4):
    print(number)
Hinglish Explanation

Same print() line ko manually three times likhne ke bajay loop us block ko automatically repeat karta hai.

Try your first loop →

The for loop

Python for loop an iterable se values one by one leta hai.

for-loop.pyPython
courses = ["HTML", "CSS", "Python"]

for course in courses:
    print(course)

Har iteration me course next item ko reference karta hai.

Loop over a string

Strings iterable hoti hain, so characters one by one iterate kiye ja sakte hain.

string-loop.pyPython
for character in "Python":
    print(character)

Generate number sequences with range()

range() integer sequence represent karta hai and loops me commonly use hota hai.

range.pyPython
for number in range(5):
    print(number)

for number in range(2, 6):
    print(number)

for number in range(2, 11, 2):
    print(number)
  • range(stop) — starts at 0.
  • range(start, stop) — stop excluded.
  • range(start, stop, step) — custom step.
Boundary rule: range() ka stop value included nahi hota.

Count backwards

countdown.pyPython
for number in range(5, 0, -1):
    print(number)

print("Go!")

Negative step use karte waqt start/stop direction compatible honi chahiye.

The while loop

while tab tak repeat karta hai jab tak condition truthy rahe.

while.pyPython
count = 1

while count <= 5:
    print(count)
    count += 1
Important: Condition ko eventually false banane wali state update karna zaroori hai, warna infinite loop ho sakta hai.

Try while loop →

for vs while

  • for: iterable ke items ya known sequence par iterate karna ho.
  • while: repetition kisi changing condition par depend kare.

Known collection ke liye manual index-based while ke bajay direct for often clearer hota hai.

Stop early with break

break nearest loop ko immediately exit karta hai.

break.pyPython
for number in range(1, 10):
    if number == 5:
        break
    print(number)

Output 1 to 4 tak hoga.

Skip an iteration with continue

continue current iteration ka remaining block skip karke next iteration par chala jata hai.

continue.pyPython
for number in range(1, 7):
    if number % 2 == 0:
        continue
    print(number)

Only odd numbers print honge.

pass inside loops

pass no-op placeholder hai; unlike continue, it next iteration par jump nahi karta.

pass-loop.pyPython
for item in range(3):
    pass

print("Loop finished")

Loop else

Python loops optional else support karte hain. else tab run hota hai jab loop normal completion kare; break se exit hone par nahi.

loop-else.pyPython
target = 7

for number in range(1, 6):
    if number == target:
        print("Found")
        break
else:
    print("Not found")
Use case: Search loops me “not found” logic ko extra flag ke bina express kar sakta hai.

Nested loops

Ek loop ke andar another loop ho sakta hai.

nested.pyPython
for row in range(1, 4):
    for column in range(1, 4):
        print(row, column)

Outer loop ki each iteration ke liye inner loop fully run hota hai. Large nested loops expensive ho sakte hain.

Running totals with an accumulator

sum-loop.pyPython
total = 0

for number in range(1, 6):
    total += number

print(total)

Accumulator variable each iteration me updated result store karta hai. Built-in sum() bhi many simple cases me better choice ho sakta hai.

Counting matches

count-matches.pyPython
scores = [82, 45, 91, 67, 38]
passed = 0

for score in scores:
    if score >= 40:
        passed += 1

print("Passed:", passed)

Get index and value with enumerate()

enumerate() manual index counter ke bajay readable index + value pairs deta hai.

enumerate.pyPython
courses = ["HTML", "CSS", "Python"]

for position, course in enumerate(courses, start=1):
    print(position, course)

Manual index += 1 se cleaner hota hai jab index actually needed ho.

Loop over multiple iterables with zip()

zip.pyPython
names = ["Aman", "Riya", "Kabir"]
scores = [82, 91, 74]

for name, score in zip(names, scores):
    print(name, score)

Default zip() shortest iterable khatam hote hi stop karta hai, so unequal lengths silently ignore extra items kar sakti hain.

Repeated input with while

retry.pyPython
attempts = 0

while attempts < 3:
    answer = input("Type yes: ").strip().lower()
    if answer == "yes":
        print("Accepted")
        break
    attempts += 1
else:
    print("No attempts left")

Run retry example →

Infinite loops

while True intentionally useful ho sakta hai when loop explicitly break se terminate hota ho, but accidental infinite loops avoid karo.

sentinel.pyPython
while True:
    command = input("Command (quit to stop): ").strip().lower()
    if command == "quit":
        break
    print("You typed:", command)
Safety: Online runners time limits laga sakte hain. Production code me clear termination condition important hai.

Changing a collection while iterating

Same collection ko iterate karte waqt uski structure mutate karna surprising behavior create kar sakta hai.

safe-filter.pyPython
numbers = [1, 2, 3, 4]

for number in numbers.copy():
    if number % 2 == 0:
        numbers.remove(number)

print(numbers)

Often better approach new collection build karna ya later comprehensions use karna hota hai.

Common beginner mistakes

  • range() stop value ko included assume karna.
  • while condition ki state update bhoolkar infinite loop banana.
  • break aur continue ka difference confuse karna.
  • pass ko continue samajhna.
  • Unnecessary manual index counters use karna instead of enumerate().
  • Deep nested loops without need.
  • Loop ke andar repeated expensive work karna jab outside ho sakta ho.
  • Same list ko unsafe way se mutate karte hue iterate karna.
  • zip() unequal lengths ka behavior ignore karna.
  • Simple built-ins like sum() available hone par manual loop overuse karna.

Beginner best practices

  • Collection iteration ke liye direct for prefer karo.
  • Condition-driven repetition ke liye while use karo.
  • Clear loop variable names rakho.
  • Boundary values and empty iterables test karo.
  • break/continue ko readability improve karne ke liye use karo, control flow hide karne ke liye nahi.
  • Index required ho to enumerate() dekho.
  • Parallel data iterate karna ho to zip() consider karo.
  • Loop body ko short aur understandable rakho.

Chapter checklist

  • for loop se iterable traverse kar sakte ho?
  • range() ke start, stop, step clear hain?
  • while loop safely write kar sakte ho?
  • break, continue, pass ka difference clear hai?
  • Loop else kab run hota hai samajh aaya?
  • Nested loop aur accumulator pattern use kar sakte ho?
  • enumerate() aur zip() ka purpose clear hai?

Practice Task — Student Marks Analyzer

BrounStack Playground me marks analyzer banao.

  1. Five marks stdin se read karo.
  2. Har mark ko float me convert karo.
  3. Loop se total calculate karo.
  4. Average calculate karo.
  5. Highest aur lowest mark track karo.
  6. 40 ya usse zyada marks ko pass count karo.
  7. 40 se kam marks ko fail count karo.
  8. enumerate() use karke Subject 1, Subject 2... labels print karo.
  9. Invalid 0–100 range detect karo.
  10. At least one continue ya break meaningful way me use karo.
  11. Readable f-string summary print karo.
  12. Boundary values 0, 40 and 100 test karo.
  13. Final clean version ko Playground me run karo.

Open practice starter →