livepython.net
CHAPTER 11While Loops
11.1  WHILE

Python while Loop: Repeat While a Condition Is True

What Is a while Loop?

A while loop repeats a block of code as long as its condition is True. When the condition becomes False, the loop stops and Python carries on with the line below it.

PYTHONedit me
count = 1
while count <= 3:
    print("Hello, Sunny!", count)
    count += 1
print("Done")
OUTPUT
Hello, Sunny! 1
Hello, Sunny! 2
Hello, Sunny! 3
Done

Think of it like eating a bowl of soup: while there's soup in the bowl, take another spoonful. You don't count the spoonfuls first. You keep going until the bowl is empty, then you stop.

A while is an if that repeats

A while line looks almost exactly like an if line from chapter 8: a condition, a colon, an indented block. The difference is what happens after the block:

ifwhile
checks the conditiononcebefore every round
runs the block0 or 1 times0, 1 or many times
after the blockcarries on belowgoes back up and checks again

Each trip through the block is called a round (programmers also say an iteration).

  1. Start:
    Start
  2. Step:
    count = 1
  3. Decision:
    Is count 3 or less?
    yes
    Say hello, add 1 to count, then ask again
    no
    Leave the loop
  4. Input or output:
    Show: Done
  5. End:
    End
Say hello three times

Different from a for loop

In chapter 10, a for loop went through the items of a list, a string or a range(). A while loop needs none of these: it only needs a condition. That makes it the right loop when you don't know in advance how many rounds you'll need, like "keep asking until the user types done". You'll compare the two loops in topic 4.

A while loop repeats its block as long as its condition is True.

your turnPredict the output

What will this print?

n = 1 while n <= 2: print("Hi") n += 1
Your turn! What will this code show on the screen?
your turnPick the right idea

What is the big difference between if and while?

Think about it, then pick one.

How a while Loop Runs, Step by Step

A while loop follows the same three steps every round: check the condition, run the whole block, go back to the check. It stops at the first check that gives False.

Think of a guard at a gate who asks the same question each time someone comes back: "Still got your ticket?" Yes, and you go round again. No, and you're out.

The rules

  • The line is while condition:, with a colon at the end, just like if.
  • The block under it is indented by 4 spaces.
  • The condition is checked only at the top, before each round.
  • When it's False, Python jumps to the first line after the block.

Trace it

Here's a loop that adds up 1 + 2 + 3 + 4:

PYTHONedit me
total = 0
n = 1
while n <= 4:
    total += n
    n += 1
print(total)
OUTPUT
10

Follow the values round by round. This is called tracing a loop, and it's the best way to understand one (remember debugging from chapter 3?):

Roundn at the checkn <= 4?total after the round
11True1
22True3
33True6
44True10
-5Falseloop ends

It may run zero times

If the condition is False at the very first check, the block never runs:

PYTHONedit me
n = 10
while n < 5:
    print("inside")
print("after")
OUTPUT
after

Avoid: forgetting the colon

PYTHONedit me
n = 1
while n <= 3
    print(n)
    n += 1
OUTPUT
SyntaxError: expected ':'

Same error as a missing colon after if. Python tells you exactly what's missing.

Common beginner doubt: "Does the loop stop the moment the condition turns False, in the middle of the block?" No. Python finishes the whole block first, and only stops at the next check.

Check, run the whole block, check again. The loop ends at the first False check.

your turnType the output

Type what this prints

x = 10 while x < 5: print("in") print("out")
Read the code line by line, then type the output exactly.
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Counting Up and Down with while

The most common while loop is a counter loop: a variable that counts the rounds, and a condition that stops it at the right number.

PYTHONedit me
count = 1
while count <= 5:
    print(count)
    count += 1
OUTPUT
1
2
3
4
5

Think of climbing stairs: you start on step 1, you check if you've reached the top, and if not, you climb one more step.

The three parts of a counter loop

PartIn the exampleWhat it does
Startcount = 1gives the counter its first value, before the loop
Checkwhile count <= 5:decides if there's another round
Changecount += 1moves the counter, inside the loop

Forget one of the three, and the loop breaks. A missing change is the worst: the loop never ends. That's the whole next topic.

Counting down

Start high, check > 0, and use -= (chapter 5) to count down:

PYTHONedit me
n = 5
while n > 0:
    print(n)
    n -= 1
print("Liftoff!")
OUTPUT
5
4
3
2
1
Liftoff!

Counting in steps

The change doesn't have to be 1. Add 2 each round to get the even numbers:

PYTHONedit me
n = 2
while n <= 10:
    print(n)
    n += 2
OUTPUT
2
4
6
8
10

Common beginner doubt: "Couldn't I do this with for and range()?" Yes! for count in range(1, 6): prints the same 1 to 5, in fewer lines, and it can't forget the change. For plain counting, a for loop is usually the better pick. Learning to count with while shows you how every loop works inside, and you'll need these three parts for the loops that for can't do.

A counter loop needs a start, a check and a change.

your turnFill the gap

Complete the countdown: 3, 2, 1

n = 3 while n ? 0: print(n) n -= 1

It should print: 3 2 1

Which piece makes this code work?
your turnPredict the output

What will this print?

n = 1 while n < 10: print(n) n += 4
Your turn! What will this code show on the screen?

Loop Until a Goal Is Reached

The real power of while shows when you don't know how many rounds you need. You know the goal, so you put it in the condition and let the loop find the number of rounds for you.

Think of filling a bucket with a cup: you don't know how many cups it takes. You keep pouring while the bucket isn't full.

How many weeks?

Rocky's plant is 2 cm tall, and it doubles in height every week. How many weeks until it's taller than 100 cm?

PYTHONedit me
height = 2
weeks = 0
while height <= 100:
    height *= 2
    weeks += 1
    print(f"Week {weeks}: {height} cm")
print(f"Taller than 100 cm after {weeks} weeks")
OUTPUT
Week 1: 4 cm
Week 2: 8 cm
Week 3: 16 cm
Week 4: 32 cm
Week 5: 64 cm
Week 6: 128 cm
Taller than 100 cm after 6 weeks

Nobody told the loop "run 6 times". It ran until the goal was met, and the counter weeks remembered how many rounds that took.

Chop off the digits

Here's a classic: count the digits of a number. Remember // from chapter 5? 4728 // 10 is 472: it chops off the last digit. Keep chopping until nothing is left:

PYTHONedit me
n = 4728
digits = 0
while n > 0:
    n = n // 10
    digits += 1
print("Digits:", digits)
OUTPUT
Digits: 4

n goes 4728, 472, 47, 4, 0. Four rounds, four digits. It works the same for a number with 2 digits or 20.

The pattern

  • Put the goal in the condition: "while not there yet".
  • Make each round move a step toward the goal.
  • Use a counter if you need to know how many rounds it took.
  • Print the answer after the loop, when the goal is reached.

Common beginner doubt: "Why does the condition say <= 100 when the goal is over 100?" The condition is when to keep going, not when to stop. Keep going while the height is 100 or less; stop once it's over.

Use while when you know the goal, but not how many rounds it takes.

your turnOrder the lines

Put the lines in order to print 64: keep doubling while the number is under 50

  1. height *= 2
  2. height = 2
  3. while height < 50:
  4. print(height)
These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

scores = [4, 9, 2] scores.append(7) print(len(scores), max(scores))
Your turn! What will this code show on the screen?

Practice: while

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 90.Python Program to Print Numbers from 1 to N Using a While LoopEasySolve
  2. 91.Python Program to Print a Countdown with a While LoopEasySolve
  3. 92.Python Program to Find the Sum of Digits of a NumberMediumSolve