for loops and range()
A for loop goes through a sequence one item at a time, running the block once for each item.
for letter in "hey":
print(letter)
That prints h, e, y on three lines. The variable letter is created by the loop and gets the next item each round. You choose its name.
To repeat something a set number of times, loop over range():
range(5)gives 0, 1, 2, 3, 4. Five numbers, starting at 0, stopping before 5.range(1, 6)gives 1, 2, 3, 4, 5.range(0, 20, 5)gives 0, 5, 10, 15. The third number is the step.range(5, 0, -1)counts down: 5, 4, 3, 2, 1.
The "stops before the end" rule is the same as slicing, and it is the source of countless off-by-one bugs. If you want 1 to 10, you write range(1, 11). Say it out loud until it feels normal.
A very common pattern is the accumulator: start a variable at zero before the loop, then add to it inside.
total = 0
for n in range(1, 4):
total += n
print(total) # 6
Notice the print is not indented, so it runs once, after the loop. Indent it and it runs every round. Indentation decides what is inside the loop.
for or while? If you can say "for each thing in this collection" or "this many times", use for. If it is "until something happens", use while. A for loop can never accidentally run forever over a range, which is a nice bonus.
Try it yourself
Edit it. Break it. Run it again.for letter in "hey":
print(letter)
for i in range(5, 0, -1):
print(i, end=" ") # end=" " keeps everything on one line
print("go!")
total = 0
for n in range(1, 101):
total += n
print("1 + 2 + ... + 100 =", total)
Your turn
Type it yourself. That is the whole trick.1Times table
Print the 7 times table from 7 x 1 = 7 up to 7 x 5 = 35, one line each, using a for loop and range().
for i in range(5):
print(f"7 x {i} = {7 * i}")
2Count the vowels
Loop over the string text and count how many of its characters are vowels (a, e, i, o, u). Print the count. For the given text the output is 8.
text = "programming is fun actually" count = 0 print(count)