Loops
Basics9 min readLesson 7 of 8
A loop runs the same indented block more than once. Python has two common forms. A for loop takes items from a sequence one at a time, such as a list or a range of numbers. A while loop repeats as long as a condition stays True. Writing the same lines by hand makes a program harder to change.
for step in range(1, 4):
label = f'Step {step}'
print(label)Output
Step 1 Step 2 Step 3
7.1 Choosing the form
- Use
forwhen the amount of work is known. - Use
whilewhen the stopping point depends on something that changes inside the loop. - Add a line inside every
whileloop that moves the condition towardFalse.
7.2 How range counts
range(1, 4) produces 1, 2, and 3; the second number is a stopping point that is not included. To include the endpoint, add one: range(1, 5) gives 1 through 4. A loop variable, here step, takes a new value on each pass. Indented lines repeat, and an unindented line after the block runs once.
count = 3
while count > 0:
print(count)
count -= 1
print('lift off')Output
3 2 1 lift off
7.3 Common mistake
A while loop that never changes the variable in its condition keeps running. The body may run without end, and the terminal keeps printing until you interrupt it. Check that one line inside the loop moves the count or state toward the stopping condition. A for loop avoids that risk for simple counting, though its range still stops before the second number.
total = 0
for n in [2, 4, 6]:
total += n
print(total)Output
12
7.4 Practice
- Use a
forloop to print the squares of1through5. - Rewrite the same loop with
whileand keep a running total. - Print the total after the loop ends.
If the while version hangs, stop it and check which line is supposed to change the counter.
