← Intro to programming with Python
for loops and range()
Repeat a set number of times, or go through each item.
A for loop walks through a sequence one item at a time, and runs its indented lines for each one. range() makes a sequence of numbers: range(5) is 0, 1, 2, 3, 4 (five numbers, starting at 0, stopping before 5). range(1, 6) is 1 to 5. range(0, 20, 5) counts in steps of 5. A for loop can also walk through the letters of a string. Use for when you know how many times to repeat; it is shorter and safer than while, because there is no counter to forget.
for i in range(3):
print("Hip hip hooray!")
for n in range(1, 6):
print(n, "squared is", n ** 2)
for letter in "hey":
print(letter.upper())The first loop runs 3 times. In the second, n is 1, then 2, up to 5. In the third, letter is h, then e, then y.
Common mistake: expecting range(1, 10) to include 10. The stop number is never included, just like slicing. Use range(1, 11) to reach 10.
The loop variable (i, n, letter) is a normal variable. Pick a name that describes each item.