Python Core Lesson 1 of 12

Python while loops

20 min, 7 exercisesOCR 2.2.1AQA 3.2.2Edexcel 6.2.2

Builds on lessons 1 to 7. Start at lesson 1

Learn

How a while loop runs

A while loop repeats a block as long as its condition is true.

count = 3
while count > 0
    print(count)
    count = count - 1
endwhile
print("Liftoff!")
count ← 3
WHILE count > 0
    OUTPUT count
    count ← count - 1
ENDWHILE
OUTPUT "Liftoff!"
count = 3
while count > 0:
    print(count)
    count = count - 1
print("Liftoff!")

Here is exactly what happens: Python checks count > 0. True, so it runs the indented block, then jumps back up and checks again. When the condition finally comes out false, it skips the block and carries on with the line after the loop. The condition is only checked at the top of each round, not halfway through.

The block must change something that the condition depends on. Delete the line count = count - 1 and count stays 3 forever, so the condition never becomes false. That is an infinite loop, and your program will hang until you stop it. Everyone writes one eventually; consider it a rite of passage.

Learn

Shortcuts and break

A shortcut you will see everywhere: count -= 1 means count = count - 1. Same for +=, *= and friends.

Sometimes you do not know in advance when to stop. Then you can write while True: (a loop that would run forever) and use break to jump out from inside:

while True:
    guess = input()
    if guess == "42":
        break

while is the right tool when you are repeating "until something happens": until the user types the right password, until a number gets small enough, until the game is over. When you know how many times to repeat, or you are going through a collection of things, the for loop in the next lesson is usually cleaner.

GCSE exam boards
  • OCR 2.2.1 Programming fundamentals
  • AQA 3.2.2 Sequence, selection, iteration
  • Edexcel 6.2.2 Selection and repetition

Try

Run it: a countdown and doubling

The example is already in the editor. Run it, change one thing, and run it again.

In exam pseudocode
count = 3
while count > 0
    print(count)
    count = count - 1
endwhile
print("Liftoff!")
n = 1
steps = 0
while n <= 1000
    n = n * 2
    steps = steps + 1
endwhile
print(str(steps) + " doublings gives " + str(n))
count ← 3
WHILE count > 0
    OUTPUT count
    count ← count - 1
ENDWHILE
OUTPUT "Liftoff!"
n ← 1
steps ← 0
WHILE n ≤ 1000
    n ← n * 2
    steps ← steps + 1
ENDWHILE
OUTPUT INT_TO_STRING(steps) + " doublings gives " + INT_TO_STRING(n)
count = 3
while count > 0:
    print(count)
    count -= 1
print("Liftoff!")

# How many times can we double 1 before passing 1000?
n = 1
steps = 0
while n <= 1000:
    n *= 2
    steps += 1
print(f"{steps} doublings gives {n}")
example.py to run
count = 3
while count > 0:
    print(count)
    count -= 1
print("Liftoff!")

# How many times can we double 1 before passing 1000?
n = 1
steps = 0
while n <= 1000:
    n *= 2
    steps += 1
print(f"{steps} doublings gives {n}")

Practice

Count by threes

Use a while loop to print the numbers 3, 6, 9, 12 and 15, each on its own line.

Constraint

  • Work it out with code. Printing the answer as text doesn't count.
exercise_1.py to run
n = 3
while n <= 15:
    print(n)
    n += 1

Practice

Guess the password

Keep reading lines with input() until someone types open sesame. For every wrong guess print Nope. When the right guess arrives, print Welcome in and stop. With the given input, the output is two Nope lines then Welcome in.

Your program reads the Input box under the editor.

exercise_2.py to run
guess = input()
print("Welcome in")

PracticePredict the output

Halving until one

Type exactly what this prints. Track n on paper, one round at a time.

exercise_3.py
n = 10
while n > 1:
    n = n // 2
    print(n)

Break/fixFix the bug

The loop that never runs

The player starts with 3 lives and should see each one counted down before Game over. Instead the program goes straight to Game over.

Constraint

  • Work it out with code. Printing the answer as text doesn't count.
exercise_4.py to run
lives = 3
while lives == 0:
    print("Lives left:", lives)
    lives -= 1
print("Game over")

Practice

Add up until done

Read numbers, one per line, until someone types done. Then print the total and how many numbers there were, exactly like the examples. If done comes first, both are 0.

Milestones

  1. Three numbers
  2. Nothing typed
  3. One number

Your program reads the Input box under the editor. Check also tries 2 other inputs.

exercise_5.py to run
total = 0
items = 0

Practice

Skip the empty scans

break leaves a loop. Its partner is continue: it skips the rest of the block for this round only and jumps back to the top of the loop, where the condition is checked again.

while True:
    line = input().strip()
    if line == "":
        continue        # nothing to do with an empty line: next round
    print("Got", line)

A ticket scanner at a gig sends one code per line until it sends close. Sometimes it sends an empty line (or one with only spaces) by mistake. Print Scanned: and the code for every real code, skip the empty lines with continue, then print how many tickets were scanned.

Constraint

  • Use continue to skip the empty lines.

Milestones

  1. Two empty lines
  2. Nothing scanned

Your program reads the Input box under the editor. Check also tries 1 other inputs.

exercise_6.py to run
count = 0
while True:
    code = input().strip()
    if code == "close":
        break
    print("Scanned:", code)
    count += 1
print("Tickets:", count)

Your turn

Level up from XP

In a game, going from level 1 to level 2 costs 100 XP, and each level after that costs double the one before: 200 XP to reach level 3, 400 to reach level 4, and so on. Read a player's total XP (a whole number). Spend it on levels for as long as there is enough, then print the level they reached and how much more XP the next level needs, like the examples.

Milestones

  1. 350 XP
  2. A brand new player
  3. Exactly one level
  4. Exactly four levels
  5. One short

On your own. Hints open after your first check.

Your program reads the Input box under the editor. Check also tries 4 other inputs.

exercise_7.py to run
Python 3.13

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.