devnotes.

for and while Loops

Python's for loop iterates over any iterable directly — there's no C-style counting loop as the default, since it's rarely needed.

fruits = ["apple", "mango", "banana"]
for fruit in fruits:
    print(fruit)

for i in range(5):          # range(5) produces 0, 1, 2, 3, 4
    print(i)

for i in range(2, 10, 2):    # start, stop, step -> 2, 4, 6, 8
    print(i)

for index, fruit in enumerate(fruits):   # get both index and value
    print(index, fruit)

n = 5
while n > 0:
    print(n)
    n -= 1

for item in iterable: directly gives you each element, unlike C or Java's index-based loops — this is possible because Python's for loop works with any object implementing the iterator protocol (covered in the Functional Patterns chapter), which includes lists, strings, dicts, sets, files, and more.

range(stop), range(start, stop), and range(start, stop, step) generate a sequence of numbers lazily (without building a full list in memory) — the classic way to loop a specific number of times, or with a numeric index when one is genuinely needed.

enumerate(iterable) is the idiomatic way to get both the index and the value while looping — reaching for a manual counter variable (i = 0; ... i += 1) inside a Python loop is a strong signal that enumerate (or a different construct entirely) is the better fit. while loops behave as in most languages, checking their condition before each iteration.

for and while Loops in Python | DevNotes