Loops repeat an action for you.
A loop lets Python repeat a block of code. This saves you from writing the same instruction many times and makes it easier to work through a group of values.
for number in range(5):
print(number)range(5) produces 0, 1, 2, 3, and 4. The indented line runs once for each number; the stop value 5 is not included.
0
1
2
3
4Use range(start, stop) when you want a different start. The start is included and the stop is not. You can also add a step: range(0, 10, 2) produces every second number from 0 to 8.
Indentation still matters: The code inside a for or while loop must be indented. Python uses that indentation to know which instructions repeat.
count = 1
while count <= 3:
print(count)
count += 1A while loop checks its condition before every iteration. Here, count += 1 is shorthand for count = count + 1, so the condition eventually becomes false and the loop ends.
for number in range(5):
if number == 3:
break
print(number)break immediately ends the loop. This prints 0, 1, and 2, then stops when the number is 3.
for number in range(5):
if number == 2:
continue
print(number)continue skips the rest of the current iteration and moves to the next one. This prints 0, 1, 3, and 4.
count = 1
while count > 0:
print(count)
count += 1This loop never makes count > 0 false, so it keeps running. Make sure a while loop can eventually reach a false condition.
