Loops
🔁 Loops
for and while loops, range(), loop control with break/continue, a genuinely unusual Python feature (the loop else clause), and enumerate().
🔂 for Loops: Iterating Over a Sequence
Python's for iterates directly over items in a sequence — not an index counter, unlike a C-style for:
Looping: Go vs Kotlin vs Python
Go uses a single for keyword for every loop shape (counting, condition-based, infinite) — there's no separate while at all. Kotlin's for (item in collection) is directly comparable to Python's item-based for. Python keeps for (iterate over items) and while (loop on a condition) as two distinct keywords.
🔢 range(): Looping a Specific Number of Times
range(n)'s stop value is always exclusive — range(5) produces 0, 1, 2, 3, 4, five numbers total, never 5 itself. This trips up nearly everyone the first time they need exactly n iterations and reach for range(n) expecting it to count up to n inclusive.
🔄 while Loops
Python has no do-while construct at all — the condition is always checked before the loop body runs, at least once via while or not at all.
⏭️ break and continue
🎯 The Loop else Clause
A genuinely distinctive Python feature: for and while loops can have an else clause that runs only if the loop finishes without hitting a break — useful for search patterns:
Neither Go nor Kotlin has anything like this — it's a Python-specific idiom worth recognizing when reading other people's code, even if you don't reach for it constantly yourself.
🔢 enumerate(): Getting the Index While Iterating
enumerate() pairs each item with its index automatically — no separate counter variable to manually increment, the way a C-style loop would need.
for
Iterates directly over items in a sequence — strings, lists, range(), and more.
while
Loops on a condition, checked before each iteration; no do-while equivalent exists.
break / continue
Exit the loop entirely, or skip straight to the next iteration.
enumerate()
Pairs each item with its index — no manual counter variable needed.
💻 Coding Challenges
Challenge 1: Sum of Even Numbers
Using range() and a for loop, calculate and print the sum of all even numbers from 1 to 20 (inclusive).
Goal: Practice combining range(), the modulo operator, and loop accumulation.
Challenge 2: Search With Loop else
Given a list of names, write a for loop with a matching else clause that prints "found!" and breaks if a target name is in the list, or prints "not found" via the else clause if it never is.
Goal: Get hands-on with the loop else clause in the exact search scenario it's designed for.
Challenge 3: Numbered List Output
Given a list of three favorite foods, use enumerate() to print each one with a 1-based number in front of it (e.g. "1. Pizza"), not the default 0-based index.
Goal: Practice using enumerate() and adjusting its default starting index for a human-friendly numbered list.
🎯 What's Next
Next chapter: Strings & String Formatting — slicing, string methods, f-strings, and .format().