18. Loops
The other way out of repeating yourself is the loop:
a block of code that runs over and over. Python has two main loop shapes
— while and for — plus break for
stopping early. All covered here.
while —
repeat as long as the condition is true
while is the most general loop. It checks a condition,
runs the block if true, then checks again — repeating until it is
false.
count = 10
while count > 0:
print(count)
count = count - 1
print("Blast off!")Run order:
- Check
count > 0. It is10, so True. - Print
10, setcountto9. - Back to step 1.
countis9, still True. Print, decrement. - Repeat until
countis0. The condition fails, the loop exits, andprint("Blast off!")runs once.
Inside the body, change a value the condition depends on, or the loop never ends. An infinite loop locks the terminal. Stop it with Ctrl + C.
for — repeat a
known number of times
The for loop is the right tool when you know how many
times to repeat, or when you want to step through a sequence. The shape
uses range():
for i in range(1, 6):
print(i)Output:
1
2
3
4
5
range(start, stop) produces numbers from
start up to — but not including —
stop. So range(1, 6) gives
1, 2, 3, 4, 5. This is one of the first surprises in
Python: the end value is excluded.
To loop from 1 to 10, write range(1, 11).
A step
A third argument to range() is the step
— how much the counter changes each round. The default is
1; change it to skip or count backwards:
for i in range(0, 101, 10): # 0, 10, 20, ... 100
print(i, end=" ")
print() # a blank line at the end
for i in range(10, 0, -1): # 10, 9, 8, ... 1
print(i, end=" ")
print()The step needs the right sign — positive going up, negative
going down. A step of 0 raises a
ValueError.
print(i, end=" ") tells Python to print a space after
each value instead of a newline. The plain print() at the
end starts a new line.
Open exercises/18/01-for-table.py. It prints the
multiplication table of 7, from 7 * 1 to
7 * 10. Change it to print the table of any other
number.
while True: with
break
Any loop can be cut short with break, which jumps
straight to whatever comes after the loop. A while True:
loop has no built-in exit; the only way out is break:
n = 1
while True:
if n * n > 100:
break
n = n + 1
print("First number whose square is over 100 is", n)Use while True: when the exit test is too complicated
for a single comparison at the top.
Running at least once
with while True:
Sometimes you need the loop body to run at least once before checking
the condition. Use while True: and break at
the end:
# runs at least once, stops when count > 5
count = 1
while True:
print(count)
count = count + 1
if count > 5:
breakThe break at the bottom exits as soon as the condition
is met.
Homework
Problem 1 — Count to 20
Open exercises/18/homework/01-count-to-20.py. Use a
while loop to print 1 to 20, each on its own line.
Problem 2 — Multiplication table of 7
Open exercises/18/homework/02-mult-table-7.py. Use a
for loop with range() to print the
multiplication table of 7, from 7 * 1 to
7 * 12, in this shape:
7 * 1 = 7
7 * 2 = 14
...
7 * 12 = 84
Problem 3 — Stop at the threshold
Open exercises/18/homework/03-stop-at-threshold.py. Loop
from 1, adding each number to a running total. Stop once the total
exceeds 100, then print the total and the counter value at that
moment.
Challenge — Sum 1..N
Open exercises/18/homework/04-sum-1-to-n.py. Prompt for
a positive whole number n. Compute
1 + 2 + 3 + ... + n with a for loop and a
running total. Print:
Sum from 1 to N is S
Then print the formula n * (n + 1) // 2 on the next line
— the closed-form answer. The two should agree.
Stuck or finished? Open the homework solutions page.