You repeat instructions with for and while, and control your loops with range, break, and continue.
Open this lesson in KodokonA loop repeats a block of instructions several times, without you having to copy it out again. The for loop repeats a number of times known in advance. It's often used with range, a function that produces a sequence of numbers: range(5) gives 0, 1, 2, 3, 4 (you start from 0 and the end bound is excluded). As with if, the line ends with : and the repeated block is indented by 4 spaces.
for number in range(5):
print(number)range also accepts a start: range(1, 6) gives 1, 2, 3, 4, 5. The while loop repeats its block as long as a condition is true. You use it when you don't know in advance how many rounds there will be. Careful: the block must make the condition evolve, otherwise the loop never stops.
countdown = 3
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Go!")Two keywords let you control a loop from the inside: break exits immediately from the loop, and continue skips to the next round without running the rest of the block. In the example below, % gives the remainder of a division: number % 2 == 0 therefore tests whether a number is even.
for number in range(10):
if number == 5:
break
if number % 2 == 0:
continue
print(number)for i in range(3): run?break keyword do in a loop?while condition stays true forever?