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.

Worked example

1total = 0​
2for n in range(1, 6):​
3 total += n​
4print(total) # 15​

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

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

Lesson test

Take an 8-question test on “for & while Loops” — concepts, output prediction, bug spotting and interview questions.