AnyCompiler

for Loops

A for loop runs a block of code once for every item in a collection. Unlike some languages, Python's for loop doesn't need an index variable or a manual counter — it just hands you each item directly.

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
Output
apple
banana
cherry

Looping a specific number of times with range()

When you want to repeat something N times rather than loop over an existing collection, range() generates a sequence of numbers for you to loop over.

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

range(5) counts from 0 up to (not including) 5 — five numbers total. You can also give range() a start, stop, and step: range(2, 10, 2) counts from 2 to 10 in steps of 2.

for i in range(2, 10, 2):
    print(i)
Output
2
4
6
8

Next: while loops — repeating based on a condition instead of a fixed collection.

Practice exercise

Use a for loop with range() to print the numbers 1 through 5, each on its own line.