The for loop#
A for loop goes through the items of a sequence (string, list, tuple, range...) one by one. You don't manage a counter yourself.
for variable in sequence:
# body runs once for each item
In each round (called an iteration), the loop variable fruit holds the next item: first "apple", then "mango", then "banana".
Looping over a string#
A string is a sequence of characters:
The range() function#
range() generates a sequence of numbers - perfect for "repeat N times".
| Form | Meaning | Example | Numbers produced |
|---|---|---|---|
range(stop) |
0 up to stop-1 | range(5) |
0 1 2 3 4 |
range(start, stop) |
start up to stop-1 | range(2, 6) |
2 3 4 5 |
range(start, stop, step) |
jump by step | range(1, 10, 2) |
1 3 5 7 9 |
| negative step | count down | range(5, 0, -1) |
5 4 3 2 1 |
range() की सबसे ज़रूरी बात: आखिरी संख्या (stop) शामिल नहीं होती।
range(5)→ 0, 1, 2, 3, 4 (5 नहीं आता)range(1, 11)→ 1 से 10 तक (11 नहीं आता)
इसलिए 1 से n तक चलाना हो तो range(1, n + 1) लिखें। तीसरा number step है - यानी हर बार कितना बढ़ाना (या घटाना) है।
Repeat something N times#
Sum of 1 to N#
for vs while#
for loop |
while loop |
|---|---|
| You know how many times / you have a sequence | You repeat until a condition changes |
| Counter is automatic | You manage the counter |
for i in range(10): |
while balance > 0: |
| Cannot accidentally go infinite (over a range) | Can become infinite if you forget the update |
enumerate() - index and value together#
Often you need the position as well as the item:
zip() - loop over two lists together#
zip() stops at the shortest list.
Nested loops#
A loop inside another loop. The inner loop completes all its rounds for each round of the outer loop.
Nested loop में अंदर वाला loop (inner) हर बार पूरा चलता है, फिर बाहर वाला (outer) loop एक कदम आगे बढ़ता है। जैसे घड़ी में minute की सुई पूरा चक्कर लगाती है, तब hour की सुई एक आगे बढ़ती है।
ऊपर के example में outer loop 3 बार और inner loop हर बार 3 बार चलता है, यानी कुल 3 × 3 = 9 बार print होता है।
Pattern printing#
Patterns are a great way to understand nested loops:
for...else#
Like while, a for loop can have else, which runs when the loop finishes without break:
Don't modify a list while looping over it#
Removing items from a list while looping over the same list skips items:
nums = [1, 2, 2, 3]
for n in nums:
if n == 2:
nums.remove(n)
print(nums) # [1, 2, 3] - one 2 was skipped!
Loop over a copy instead (for n in nums[:]:) or build a new list (you'll learn list comprehensions later).
Summary#
for item in sequence:visits every item of a string, list, tuple, range, etc.range(start, stop, step)- stop is excluded; userange(1, n + 1)for 1..n.enumerate()gives index + value;zip()walks several lists together.- Nested loops: the inner loop runs fully for each outer iteration.
for...else:elseruns only if the loop wasn't broken.