A for loop lets Python repeat a block of code for every item in a sequence. When you want to repeat an operation a known number of times, the range() function is usually the clearest choice.Copy
for number in range(5):
print(number)This prints 0 through 4, not 1 through 5. The starting value is included, while the stopping value is excluded. You can provide a start and stop value:Copy
for number in range(1, 6):
print(number)The third argument controls the step:Copy
for number in range(10, 0, -2):
print(number)This counts backward from 10 to 2. Use range() when the loop is based on positions or repetitions. If you already have a list of values, loop over the list directly instead of creating indexes unnecessarily.Copy
names = ["Ava", "Noah", "Mia"]
for name in names:
print(f"Hello, {name}")Common mistakes include expecting the stop value to be included, using a zero step, and modifying a list while iterating over it. Start with direct iteration, then add range() when you need a numeric sequence or an index.