L2·Control & Collections

🔁for & while Loops

Iteration over sequences and conditions.

forwhilebreakcontinuerange

§ 1for loops iterate

for x in iterable: — works on any iterable (list, str, dict, generator, file).

§ 2range

range(stop), range(start, stop), range(start, stop, step). Lazy — no list created.

§ 3break / continue / else

break exits early. continue skips to next iteration. else on a loop runs if no break fired.

Animated step-through

step 1 / 12
1total = 0
2for n in range(1, 6):
3 total += n
4print(total) # 15
Variables
total0

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
range(1, 10, 2) yields: