Curriculum / Python / Lesson 07

Loops in Python

Python has two loop types: for (used to iterate over a sequence like a list, string, or range of numbers) and while (repeats while a condition is true).

7 of 11
beginner 📖 5 min read 🎯 1 question

Loops

Python has two loop types: for (used to iterate over a sequence like a list, string, or range of numbers) and while (repeats while a condition is true). Python's for loop is fundamentally different from C/Java's — it always iterates over an iterable, not a counter.

💡 Key insight Python has no do-while loop — use a while True loop with a break condition to get the same effect.

Syntax

syntax
for item in iterable:
    # code
while condition:
    # code

Example

range(1, 6) generates the numbers 1 through 5 (the end value is excluded).

py
for i in range(1, 6):
    print(i, end=" ")
output1 2 3 4 5

Try it yourself

Copy this example into the Python compiler and run it — try changing a value and see what happens.

Quick Quiz

1. What does range(1, 6) generate in Python?

Back to curriculum