Skip to content
AgileLogics
4 min read

for Loops

Prerequisites: Loops

A for loop runs its block once for every item in a sequence.

Syntax

for item in sequence:
    ...

Example

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)

for number in range(3):
    print(number)

Expected output

apple
banana
cherry
0
1
2

range(3) generates the sequence 0, 1, 2 — three numbers, not including 3. There is no C-style for (i = 0; i < n; i++) loop in Python; for ... in range(n) is the idiomatic replacement.

Common mistakes

  • Expecting range(3) to include 3 — the end value is always exclusive.

Practice

Print each number from 1 to 5 (inclusive) using a for loop.

Show solution
for number in range(1, 6):
    print(number)