Python Basics · Repeating Work · lesson 9 of 12
while loops
about 12 minutes · free · runs in your browser
Step 1 of 2
Repeating while something is true
A while loop repeats its body for as long as a condition holds:
count = 3
while count > 0:
print(count)
count -= 1
print("Go!")
Python checks the condition, runs the body, then checks again — over and over until the condition is false.
The line that matters most is count -= 1. Something inside the loop must move the
condition towards being false. Forget it and the loop never ends; PyLearn will stop your
program after five seconds and say so, which is a much gentler lesson than a frozen tab.
Your turn: add up every whole number from 1 to limit inclusive using a while
loop, leaving the answer in total.
You start from this, and edit it in the browser:
limit = 10
total = 0
# Add every number from 1 to limit using a while loop.
Step 2 of 2
Counting with a condition
while suits problems where you do not know in advance how many steps are needed — you
only know when to stop.
n = 100
steps = 0
while n > 1:
n = n // 2
steps += 1
That counts how many halvings it takes to get down to 1. You could not write that as a simple counting loop, because the number of steps depends on the arithmetic.
Your turn: write countdown_length(n) returning how many times you can halve n
(using //) before it reaches 1 or below. For 8 that is 3.
You start from this, and edit it in the browser:
def countdown_length(n):
# Count the halvings needed to reach 1.
pass