Back to course

Introduction to Iteration: The `for` Loop

Python Programming: The 0 to Hero Bootcamp

The for Loop

While while loops are condition-controlled, for loops are typically used for iteration—going through a sequence (like a string, list, or range) element by element.

Syntax

python for item in sequence: # Code block runs once for each item in the sequence do_something_with(item)

Example: Iterating over a String

A string is a sequence of characters.

python word = "Python"

for character in word: print(f"Current letter: {character}")

Output:

Current letter: P Current letter: y Current letter: t ...

The range() Function

Since numbers are often needed for counting, the range() function generates an immutable sequence of numbers. This is the most common way to create a numeric for loop.

range(stop)

Generates numbers from 0 up to (but not including) stop.

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

range(start, stop)

Generates numbers from start up to (but not including) stop.

python for j in range(5, 10): print(j) # Output: 5, 6, 7, 8, 9

range(start, stop, step)

Generates numbers using an increment (or decrement) step.

python for k in range(0, 10, 2): print(k) # Output: 0, 2, 4, 6, 8