Counting with range
for i in range(1, 6): print("Round", i)
Write Python. Understand every error.
Python basics · topic 9 of 25
A for loop repeats a block once for every item in a sequence. With range(), you can repeat a fixed number of times.
for i in range(5): print(i) # 0 1 2 3 4
range() has three forms. The stop value is never included.
range(5) gives 0, 1, 2, 3, 4range(2, 6) gives 2, 3, 4, 5range(10, 0, -2) gives 10, 8, 6, 4, 2A common pattern is to keep a running total: start a variable at 0 before the loop and add to it inside the loop. Print it after the loop, without indentation, so it is shown once.
total = 0 for n in range(1, 6): total += n print(total) # 15
range(5) gives 0, 1, 2, 3, 4. The stop value is never included.range(start, stop, step) can start elsewhere, take bigger steps, or count down with a negative step.for line, and it runs once for each value.for item in items:, is usually clearer than counting positions.range(1, 5) to include 5. It stops at 4.range(len(items) + 1), which goes one position past the end of the list. Read the IndexError guide.
for i in range(1, 6): print("Round", i)
for i in range(0, 21, 5): print(i) for i in range(3, 0, -1): print(i) print("Go!")
total = 0 for n in range(1, 11): total += n print("Sum of 1 to 10 is", total)
for letter in "Python": print(letter)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
for i in range(3): print(i, end=" ")
range(3) gives 0, 1 and 2. The stop value is not included.
print(list(range(2, 10, 3)))
Start at 2, go up in steps of 3, stop before 10.
total = 0 for n in [4, 5, 6]: total += n print(total)
The loop adds each number: 4 + 5 + 6 = 15.
for i in range(1, 11):?range(1, 11) gives 1 to 10: ten numbers.
for ch in "abc": print(ch.upper(), end="")
A for loop visits each character of a string. end="" keeps them on one line.