Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 13

while Loops, break and continue

This lesson goes with Episode 13 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

13.1 Why we need loops

Print the numbers 1 to 5:

print(1)
print(2)
print(3)
print(4)
print(5)

Output

1
2
3
4
5

Now print 1 to 5000. Copy and paste is not a plan. And what about "print the numbers from 1 up to whatever the user types"? You cannot even write that program by copying, because you do not know how many lines to copy.

Repeating a block of code is called looping or iteration. Each single run through the block is one iteration, or one pass. Python has two kinds of loop:

  • while repeats as long as a condition is true. This chapter.
  • for repeats once for each item in a collection. The next chapter.

13.2 The while statement

count = 1
while count <= 5:
    print(count)
    count = count + 1
print("Done")

Output

1
2
3
4
5
Done

It looks almost exactly like an if: a keyword, a condition, a colon and an indented block. The difference is one single step. After an if block finishes, the program moves on. After a while block finishes, the program jumps back up and tests the condition again.

                 │
                 ▼
          ┌─────────────┐   False
     ┌───►│ count <= 5  ├──────────┐
     │    └──────┬──────┘          │
     │      True │                 │
     │           ▼                 │
     │    ┌─────────────┐          │
     │    │  the block  │          │
     │    └──────┬──────┘          │
     └───────────┘                 │
                                   ▼
                                "Done"

In words:

  1. Test the condition.
  2. If it is true, run the whole block, then go back to step 1.
  3. If it is false, skip the block and continue after the loop.

Tracing the loop

A trace table is the best way to understand any loop. Write one row per test of the condition:

Pass count when tested count <= 5 Prints count after the block
1 1 True 1 2
2 2 True 2 3
3 3 True 3 4
4 4 True 4 5
5 5 True 5 6
— 6 False the loop ends

Two things to notice. The condition is tested six times for five passes: the final test is the one that fails and ends the loop. And when the loop is over, count is 6, not 5. The loop stops because count went past the limit.

The three ingredients

Every counting loop has three parts, and forgetting any of them is a bug:

  count = 1               ◄── 1. START:     a first value for the loop variable
  while count <= 5:       ◄── 2. CONDITION: when should the loop keep going?
      print(count)
      count = count + 1   ◄── 3. UPDATE:    change what the condition tests
Forget the... What happens
start NameError: the condition uses a name that does not exist yet
condition (or get it wrong) the loop runs too many times, too few, or not at all
update the condition never becomes false: an infinite loop

The update is usually written with the shorthand from Chapter 3: count += 1.

Quick check

How many lines does this print, and what is n afterwards?

n = 10 ⏎ while n > 0: ⏎ (block) print(n) then n -= 3

Show the answer

Answer: four lines: 10, 7, 4, 1. After the fourth pass n is -2, the test -2 > 0 fails, and the loop ends. n is -2.

Practice 13.2

Predict the output

What does it print?

count = 3
while count <= 9:
    print(count)
    count = count + 3
print("Done", count)

Put the lines in order

Put the lines in order: a start, a condition, the block with the update last, and one line after the loop. The indentation of each line is fixed.

The program in the right order prints:

Target

Step 1
Step 2
Step 3
Finished
  1. print("Step", step)
  2. print("Finished")
  3. step = 1
  4. while step <= 3:
  5. step += 1

Fill in the blank

Fill in the comparison operator so that the loop prints the numbers shown in the target.

n = 1
while n  4:
    print(n)
    n += 1

The finished program prints:

Target

1
2
3
4

13.3 The condition is only checked at the top

This rule causes surprises, so it gets its own section. Python tests the condition once per pass, before the block. It does not watch the condition while the block is running.

count = 1
while count <= 3:
    count = count + 10
    print("Inside the loop, count is", count)
print("After the loop")

Output

Inside the loop, count is 11
After the loop

After the first line of the block, count is 11 and the condition is already false. But the print still runs, because the block always finishes its current pass. The condition is only looked at again when the program goes back to the top.

A loop can run zero times

Because the test comes first, the block might never run at all:

count = 10
while count <= 5:
    print(count)
print("Done")

Output

Done

The very first test, 10 <= 5, is false. This is often exactly what you want: "while there are items left to process" should do nothing when there are none.

Practice 13.3

Multiple choice

What does this program print?

stock = 0
while stock > 0:
    print("Sell one")
    stock -= 1
print("Shop closed")
Choose one answer

13.4 Infinite loops

If the condition never becomes false, the loop never ends. This is an infinite loop, and every programmer writes one sooner or later.

count = 1
while count <= 5:
    print(count)

The update is missing. count is 1 for ever, 1 <= 5 is true for ever, and the screen fills with 1s until you stop it.

Other ways to build one by accident:

count = 1
while count != 10:      # 1, 3, 5, 7, 9, 11, 13, ... jumps straight over 10
    count += 2

count = 5
while count > 0:        # going the wrong way: 6, 7, 8, ...
    count += 1

count = 1
while count <= 5:
    print(count)
count += 1              # not indented: this is AFTER the loop, so it never runs

The last one is the indentation trap from Chapter 11 in a new form. The update exists, but it is outside the block.

An infinite loop that is not a mistake

Some programs are meant to run until somebody quits them: a game, a web server, a cash machine, the Python shell itself. For those, an endless loop is the right design, and it is written openly:

while True:
    ...

True is always true, so this loop never ends by its condition. It ends from the inside, with break, which is coming in section 13.7.

Practice 13.4

Multiple choice

Each loop below starts with count = 1. Three of them end. Which one never ends?

  • Loop 1: while count < 10: with the block count += 2
  • Loop 2: while count != 10: with the block count += 2
  • Loop 3: while count != 10: with the block count += 3
  • Loop 4: while count <= 10: with the block count *= 2
Choose one answer

Multiple choice

A program is stuck in an infinite loop. What do you press, after clicking in the terminal, to stop it?

Choose one answer

13.5 The standard patterns

Most loops you will ever write are one of a few shapes. Learn the shapes and you can write a loop without thinking hard.

Counting up, down and in steps

n = 10
while n >= 0:
    print(n, end=" ")
    n -= 2
print()
print("Lift off!")

Output

10 8 6 4 2 0
Lift off!

Normally print ends by moving to a new line. end=" " tells it to end with a space instead, so the numbers appear side by side. The empty print() after the loop finishes the line. You will learn everything print can do in → Chapter 16.

Adding up: the accumulator

To total a series of values, keep a running total. Start it at zero before the loop and add to it on each pass. A variable used this way is called an accumulator.

total = 0
number = 1
while number <= 5:
    total = total + number
    number += 1
print("Sum of 1 to 5:", total)

Output

Sum of 1 to 5: 15
Pass number total before total after
1 1 0 1
2 2 1 3
3 3 3 6
4 4 6 10
5 5 10 15

The key rule: the accumulator is created before the loop. If total = 0 were inside the block, it would be reset to zero on every pass.

The starting value depends on the operation. For a sum it is 0. For a product it is 1, because multiplying by 0 would wipe everything out:

product = 1
number = 1
while number <= 5:
    product = product * number
    number += 1
print("5 factorial:", product)

Output

5 factorial: 120

Counting how many

A counter is an accumulator that goes up by one each time something happens. Here, how many numbers from 1 to 30 are divisible by 7?

found = 0
number = 1
while number <= 30:
    if number % 7 == 0:
        found += 1
    number += 1
print("Multiples of 7:", found)

Output

Multiples of 7: 4

An if inside a loop is completely normal. Notice the indentation: found += 1 is inside the if (eight spaces), while number += 1 is inside the loop but outside the if (four spaces), so it runs on every pass. Putting the update inside the if by accident would make an infinite loop.

Keeping the best so far

To find the largest value, remember the best one seen so far and replace it whenever a better one appears:

largest = 0
number = int(input("A positive number (0 to stop): "))
while number != 0:
    if number > largest:
        largest = number
    number = int(input("A positive number (0 to stop): "))
print("Largest:", largest)

Output

A positive number (0 to stop): 12
A positive number (0 to stop): 45
A positive number (0 to stop): 7
A positive number (0 to stop): 0
Largest: 45

Quick check

What is wrong with this attempt to add the numbers 1 to 100?

n = 1 ⏎ while n <= 100: ⏎ (block) total = 0, then total += n, then n += 1

Show the answer

Answer: total = 0 is inside the loop, so the total is thrown away at the start of every pass. At the end, total is just 100. The accumulator must be created before the loop.

Practice 13.5

Fill in the blank

This loop multiplies the numbers 1 to 4. Fill in the starting value of the accumulator.

product = 
number = 1
while number <= 4:
    product = product * number
    number += 1
print(product)

The finished program prints:

Target

24

Fix the bug

The user types positive prices, then 0 to stop. The program should print the largest price. Now it prints the last price that was typed. Fix it.

With the replies 12 then 45 then 7 then 0, the program prints the lines below. Your program must print exactly these lines.

Example run

Largest: 45

Write code

Sum of the even numbers. Ask for a whole number n. Print one line: the sum of the even numbers from 2 up to n (with n itself when it is even). For 10 that is 2 + 4 + 6 + 8 + 10. When n is below 2, the sum is 0.

With the reply 10, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Sum: 30

13.6 Loops that depend on the user

A counting loop knows how many passes it will make. Many loops do not: they continue until the user signals the end. A special value that means "stop" is called a sentinel.

The largest-number program above is a sentinel loop, with 0 as the sentinel. Look at its shape, because it is very common:

  number = int(input(...))        ◄── read the FIRST value before the loop
  while number != 0:              ◄── test for the sentinel
      ... use number ...
      number = int(input(...))    ◄── read the NEXT value, last in the block

The value is read in two places: once before the loop, so that the first test has something to look at, and once at the end of the block, as the update. The first read is sometimes called the priming read.

Having the same line twice is a little unsatisfying. There are two cleaner ways to write it, and you will meet both: while True with break (section 13.7) and the walrus operator (section 13.9).

A sentinel must not be real data

In the example, 0 cannot be one of the numbers. If zero were a legitimate value, you would need a different sentinel, such as an empty line or the word done. Choose a sentinel that can never be mistaken for data.

Practice 13.6

Put the lines in order

Put the lines in order to build a sentinel loop with a priming read. The word stop ends the loop and must not be printed. The indentation of each line is fixed.

With the replies tea then milk then stop, the program in the right order prints:

Target

TEA
MILK
Finished
  1. word = input("Word (stop to end): ")
  2. print(word.upper())
  3. while word != "stop":
  4. word = input("Word (stop to end): ")
  5. print("Finished")

13.7 Leaving early: break

break ends the loop immediately. The rest of the block is skipped, the condition is not tested again, and the program continues with the first line after the loop.

number = 1
while number <= 100:
    if number * number > 200:
        break
    number += 1
print("The first number whose square is above 200:", number)

Output

The first number whose square is above 200: 15

The condition allows up to 100 passes, but the loop stops as soon as it has found its answer. break almost always sits inside an if, because you want to leave only when something particular happens.

while True with break

Combine an endless loop with break and the sentinel loop needs only one input line:

largest = 0
while True:
    number = int(input("A positive number (0 to stop): "))
    if number == 0:
        break
    if number > largest:
        largest = number
print("Largest:", largest)

Output

A positive number (0 to stop): 12
A positive number (0 to stop): 45
A positive number (0 to stop): 7
A positive number (0 to stop): 0
Largest: 45

Read it as: for ever: get a number; if it is the sentinel, leave; otherwise use it. The exit test sits in the middle of the block, exactly where the decision is naturally made. This "loop and a half" is the standard Python way to write a loop whose stopping test belongs in the middle.

Asking until the answer is valid

This is the pattern promised in Chapters 6 and 10: keep asking until the user gives something usable. It combines while True, try/except and break:

while True:
    reply = input("How many tickets? ")
    try:
        tickets = int(reply)
    except ValueError:
        print("Please type a whole number.")
        continue
    if tickets <= 0:
        print("Please type a number above zero.")
        continue
    break
print(f"Booking {tickets} tickets.")

Output

How many tickets? lots
Please type a whole number.
How many tickets? -3
Please type a number above zero.
How many tickets? 4
Booking 4 tickets.

Each problem prints a message and goes round again (continue, explained next). Only a value that survives every check reaches the break. After the loop, tickets is guaranteed to be a positive whole number, and the rest of the program can rely on that.

Practice 13.7

Predict the output

What does it print?

number = 1
while number <= 50:
    if number * 7 > 30:
        break
    number += 1
print(number)

Fill in the blank

The user types points, then done. Fill in the statement that leaves the loop.

total = 0
while True:
    reply = input("Points (done to stop): ")
    if reply == "done":
        
    total += int(reply)
print("Total:", total)

With the replies 5 then 8 then done, the finished program prints:

Target

Total: 13

Write code

Ask until valid. Keep asking for a whole number from 1 to 5. When the reply is not a whole number, print Please type a whole number. and ask again. When it is a whole number outside 1 to 5, print Please type a number from 1 to 5. and ask again. When the reply is valid, stop asking and print one last line in this form: You chose 4.

With the replies six then 9 then 4, the program prints the lines below. Your program must print exactly these lines.

Example run

Please type a whole number.
Please type a number from 1 to 5.
You chose 4.

13.8 Skipping ahead: continue

continue ends the current pass and jumps straight back to the top, where the condition is tested again. The loop itself carries on.

number = 0
while number < 10:
    number += 1
    if number % 3 == 0:
        continue
    print(number, end=" ")
print()

Output

1 2 4 5 7 8 10

When number is a multiple of 3, continue skips the print for that pass.

break continue
What it ends the whole loop only the current pass
Where the program goes to the first line after the loop back to the condition
In everyday words "I am finished here." "Skip this one. Next!"

continue is never essential: you can always write if number % 3 != 0: and indent the rest. It is useful when it lets you get the "nothing to do in this case" situations out of the way at the top of the block, so that the main work is not buried inside nested ifs. The ticket example above uses it that way.

Practice 13.8

Predict the output

What does it print?

number = 0
while number < 9:
    number += 1
    if number % 4 == 0:
        continue
    print(number, end=" ")
print()

Fix the bug

This should print the numbers 1 to 6 on one line, but leave out 4. Now it stops too early. Fix it.

The program prints the lines below. Your program must print exactly these lines.

Example run

1 2 3 5 6

13.9 Assigning inside the condition: the walrus

Chapter 4 introduced the walrus operator :=, which assigns a value and gives that value back. Its best-known use is the sentinel loop, because it lets you read a value and test it in a single line:

while (word := input("Word (quit to stop): ")) != "quit":
    print(f"'{word}' has {len(word)} letters.")
print("Goodbye.")

Output

Word (quit to stop): hello
'hello' has 5 letters.
Word (quit to stop): Python
'Python' has 6 letters.
Word (quit to stop): quit
Goodbye.

Read the condition from the inside: ask for a word, name it word, then compare it with "quit". The brackets around word := input(...) are required. Without them, := would capture the result of the whole comparison, True or False, because := has the lowest priority of all.

Here are the three ways to write a sentinel loop, side by side:

Style Shape Good when
Priming read read; while value != stop: ... read again you want it to be very plain
while True + break while True: read; if stop: break; ... there are several checks or exits
Walrus while (value := read) != stop: the read-and-test fits neatly on one line

All three are correct. Pick the one that reads most clearly for the job.

Practice 13.9

Fill in the blank

Fill in the operator that gives the reply a name and hands the value on to the comparison.

while (word  input("Word (quit to stop): ")) != "quit":
    print(len(word))
print("Goodbye.")

With the replies hello then sun then quit, the finished program prints:

Target

5
3
Goodbye.

Fix the bug

This should repeat every word the user types until the word is quit. Now it prints You typed True. Fix it.

With the replies tea then milk then quit, the program prints the lines below. Your program must print exactly these lines.

Example run

You typed tea
You typed milk
Goodbye.

13.10 Taking a number apart

A classic use of while: process the digits of a whole number one at a time. The two tools come from Chapter 4:

  • n % 10 is the last digit of n.
  • n // 10 is n with its last digit removed.

Repeat until nothing is left:

number = 4729
total = 0
while number > 0:
    digit = number % 10
    total += digit
    number = number // 10
print("Sum of the digits:", total)

Output

Sum of the digits: 22
Pass number digit (% 10) total number after (// 10)
1 4729 9 9 472
2 472 2 11 47
3 47 7 18 4
4 4 4 22 0

This is a true while problem: you do not know in advance how many digits there are, and you do not need to. The loop runs until the number is used up. Note that the loop destroys number (it ends at 0). If you need the original afterwards, keep a copy before the loop.

The same skeleton reverses a number. Build the result by shifting it one place left (* 10) and adding each new digit:

number = 4729
reversed_number = 0
while number > 0:
    reversed_number = reversed_number * 10 + number % 10
    number //= 10
print(reversed_number)

Output

9274

Loops where nobody knows the count

Some loops stop when a calculation reaches a goal. How many years does it take for money to double at 7% interest a year?

balance = 1000
years = 0
while balance < 2000:
    balance = balance * 1.07
    years += 1
print(f"Doubled after {years} years: {round(balance, 2)}")

Output

Doubled after 11 years: 2104.85

And a famous puzzle. Take any positive whole number. If it is even, halve it; if it is odd, multiply by 3 and add 1. Repeat. The Collatz conjecture says you always reach 1 in the end. Nobody has ever proved it, though it has been checked for unimaginably many starting values:

number = 6
steps = 0
while number != 1:
    if number % 2 == 0:
        number = number // 2
    else:
        number = 3 * number + 1
    print(number, end=" ")
    steps += 1
print()
print("Steps:", steps)

Output

3 10 5 16 8 4 2 1
Steps: 8

This loop uses !=, against the earlier advice, because the stopping rule really is "land exactly on 1". Whether it always does is the open question.

Quick check

For n = 305, what are n % 10 and n // 10? How many passes does the digit loop make?

Show the answer

Answer: 5 and 30. Three passes: 305, then 30, then 3, then 0 ends the loop. The middle digit 0 is handled like any other.

Practice 13.10

Predict the output

What does it print?

number = 5083
count = 0
while number > 0:
    if number % 10 > 4:
        count += 1
    number //= 10
print(count, number)

Put the lines in order

Put the lines in order. The program prints the digits of 386 from the last to the first, one per line. The indentation of each line is fixed.

The program in the right order prints:

Target

6
8
3
No digits left
  1. while number > 0:
  2. print(number % 10)
  3. number = 386
  4. print("No digits left")
  5. number //= 10

Write code

Largest digit. Ask for a positive whole number. Print one line: its largest digit. Use a loop with % 10 and // 10, with no strings. For 4729 the largest digit is 9.

With the reply 4729, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Largest digit: 9

13.11 Off by one

The most common loop bug is running one pass too many or one too few. It is so common it has a name: the off-by-one error.

It comes from two small choices: where the counter starts, and whether the test uses < or <=.

Start Condition Values the block sees Passes
i = 0 i < 5 0, 1, 2, 3, 4 5
i = 1 i <= 5 1, 2, 3, 4, 5 5
i = 0 i <= 5 0, 1, 2, 3, 4, 5 6
i = 1 i < 5 1, 2, 3, 4 4

The first two are the standard forms. "Start at 0, test with <" is the Python habit, because it matches string indexes (Chapter 8). "Start at 1, test with <=" suits counting things for people.

The order of the lines inside the block matters as well:

i = 0
while i < 3:
    i += 1
    print(i, end=" ")
print()

i = 0
while i < 3:
    print(i, end=" ")
    i += 1
print()

Output

1 2 3
0 1 2

Same start, same condition, same number of passes, different values printed, because the update comes before the use in one and after it in the other.

Practice 13.11

Multiple choice

How many passes does this loop make?

i = 0
passes = 0
while i <= 4:
    passes += 1
    i += 1
print(passes)
Choose one answer

Fix the bug

This should print the squares of the numbers 1 to 5 on one line: 1 4 9 16 25. Now it starts with 0 and stops before 25. Fix it.

The program prints the lines below. Your program must print exactly these lines.

Example run

1 4 9 16 25

13.12 A float is a poor loop counter

Remember from Chapter 2 that floats are approximate. This loop looks as if it should stop when x reaches 1.0:

x = 0.0
while x != 1.0:
    x += 0.1

It never stops. Adding 0.1 ten times does not give exactly 1.0:

x = 0.0
steps = 0
while steps < 10:
    x += 0.1
    steps += 1
print(x)
print(x == 1.0)

Output

0.9999999999999999
False

x slips past 1.0 without ever being equal to it. Two rules keep you safe: count with an integer (as steps does here) and work out the float from it, or test with < so that passing the limit is enough.

Practice 13.12

Multiple choice

What does this program print?

x = 0.0
steps = 0
while steps < 3:
    x += 0.1
    steps += 1
print(x == 0.3)
Choose one answer

13.13 A brief look ahead: else on a loop

A while loop can have an else block. It runs when the loop ends because its condition became false, and is skipped if the loop was left with break:

attempts = 0
while attempts < 3:
    attempts += 1
    if attempts == 5:
        break
else:
    print("The loop finished without a break.")

Output

The loop finished without a break.

It is mainly used for searches: "look for something; if you never found it, do this". The idea is explored properly in → Chapter 15.

Practice 13.13

Predict the output

What does it print?

This uses the loop else, which is taught in Chapter 15.

tries = 0
while tries < 3:
    tries += 1
    if tries == 2:
        break
else:
    print("No break")
print("tries is", tries)

13.14 Common mistakes

The mistake What you see The fix
No update in the block The loop never ends Change the loop variable in every pass
The update is not indented The loop never ends Indent it so it is inside the block
Loop variable not created first NameError Give it a starting value before while
Accumulator created inside the loop The total keeps resetting Create it before the loop
< where <= was meant (or the reverse) One pass too few or too many Check the first and the last pass
!= with a counter that skips the target The loop never ends Use < or >
continue placed before the update The loop never ends Update before continue
if where while was meant The block runs only once while repeats; if does not
Product accumulator started at 0 The result is always 0 Start a product at 1
Comparing input text with a number sentinel The loop never stops, because "0" != 0 Convert first, or compare with "0"
A float as an exact counter The loop never ends Count with an int, or test with <
Expecting the loop to stop the instant the condition changes The pass still finishes The condition is tested only at the top

When a loop will not stop: press Ctrl+C, then add a print of the loop variable as the first line of the block and run again. You will see at once whether it is changing, and in which direction.

Practice 13.14

Fix the bug

This should count down from 3 to 1, one number per line, and then print Go!. Now it prints 3 and then Go!. Fix it.

The program prints the lines below. Your program must print exactly these lines.

Example run

3
2
1
Go!

13.15 Putting it together

Practice 13.15

Write code

Smallest divisor. Ask for a whole number above 1. Print one line: the smallest number above 1 that divides it exactly. For 91 that is 7. For 13 it is 13 itself, because no smaller number divides it. Leave the loop with break as soon as you find a divisor.

With the reply 91, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Smallest divisor: 7

13.16 How a loop works inside Python

+ Practice

Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.

Questions

Check yourself

What is the one difference between how an if and a while are carried out?

Show the answer

After the block of an if, the program continues downwards. After the block of a while, the program jumps back and tests the condition again.

Check yourself

Name the three ingredients of a counting loop. What happens if the third is missing?

Show the answer

A start (the first value of the loop variable), a condition, and an update. Without the update the condition never becomes false, so the loop is infinite.

Check yourself

When exactly is the condition of a while loop tested?

Show the answer

Once before each pass, at the top. Never in the middle of the block.

Check yourself

Can the block of a while loop run zero times? Give an example.

Show the answer

Yes: if the condition is false the very first time. For example n = 0 and while n > 0:.

Check yourself

After i = 0 and a loop while i < 4: i += 1, what is the value of i? Why is it not 3?

Show the answer

4. The loop continues while i < 4, so it can only end when i is no longer below 4.

Check yourself

Why must an accumulator be created before the loop and not inside it?

Show the answer

Lines inside the loop run on every pass. Creating the accumulator there would reset it each time.

Check yourself

What is the difference between break and continue?

Show the answer

break ends the whole loop. continue ends only the current pass and goes back to test the condition.

Check yourself

Why can continue cause an infinite while loop? How do you avoid it?

Show the answer

continue skips the rest of the block. If the update is in that skipped part, the loop variable never changes. Put the update before the continue.

Check yourself

What is a sentinel? Why must it not be a possible data value?

Show the answer

A special value that signals "stop". If it could also be real data, the loop would stop early when that data was entered.

Check yourself

Why is while x != 1.0: dangerous when x goes up in steps of 0.1?

Show the answer

Floats are approximate, so repeated additions of 0.1 never give exactly 1.0. x passes the target without ever equalling it, and the loop never ends.

Predict the output

Predict the output

i = 2
while i < 20:
    print(i, end=" ")
    i = i * 2
print()
print(i)

Predict the output

total = 0
n = 5
while n > 0:
    total += n
    n -= 2
print(total, n)

Predict the output

i = 0
while i < 6:
    i += 1
    if i == 2:
        continue
    if i == 5:
        break
    print(i, end=" ")
print()
print("i is", i)

Predict the output

n = 9045
count = 0
while n > 0:
    if n % 10 == 0:
        count += 1
    n //= 10
print(count)

Predict the output

x = 3
while x:
    print(x, end=" ")
    x -= 1
print()
print("x is", x)

Fix the bug

Fix the bug

This should print 1 to 5. It never stops.

The program prints the lines below. Your program must print exactly these lines.

Example run

1
2
3
4
5

Fix the bug

This should print the sum of 1 to 10, which is 55. It prints 10.

The program prints the lines below. Your program must print exactly these lines.

Example run

55

Fix the bug

This should print the numbers 1 to 10. It prints 1 to 9.

The program prints the lines below. Your program must print exactly these lines.

Example run

1 2 3 4 5 6 7 8 9 10

Fix the bug

This should keep asking until the user types 0. It never stops, even when they do.

With the replies 7 then 0, the program prints the lines below. Your program must print exactly these lines.

Example run

You typed 7

Fix the bug

This should print the odd numbers from 1 to 9. It prints 1 and then hangs.

The program prints the lines below. Your program must print exactly these lines.

Example run

1 3 5 7 9

Fix the bug

This should print 5 factorial, 120. It prints 0.

The program prints the lines below. Your program must print exactly these lines.

Example run

120

Coding problems

Write code · Easy

Countdown. Ask for a starting number and count down to 1, then print Go!

Print each number on its own line. The last line is Go!.

With the reply 5, the program prints the lines below. Your program must print exactly these lines.

Example run

5
4
3
2
1
Go!

Write code · Easy

Times table. Ask for a number and print its multiplication table from 1 to 10, one line per fact, such as 7 x 3 = 21.

Print ten lines in exactly this form: 7 x 3 = 21, with a small letter x and one space around x and =.

With the reply 7, the program prints the lines below. Your program must print exactly these lines.

Example run

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Write code · Easy

Sum to n. Ask for a positive whole number n and print the sum of 1 to n. Check your result against the formula n * (n + 1) // 2.

Print two lines: first the sum found by your loop, then the result of the formula.

With the reply 100, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Loop: 5050
Formula: 5050

Write code · Medium

Average of many. Keep asking for numbers until the user presses Enter on an empty line. Then print how many numbers were entered and their average. Do not crash if no numbers were entered.

Print how many numbers were entered first, then the average. Your messages should not contain other numbers.

With the replies 4 then 9 then 5 then , the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

3 numbers, average 6.0

Write code · Medium

Count the digits. Ask for a positive whole number and print how many digits it has, using a loop with // and not len(str(...)).

With the reply 90210, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Digits: 5

Write code · Medium

Password with three attempts. Ask for a password up to three times. Print Welcome and stop asking as soon as it is correct. After three wrong attempts, print Account locked.

Use the password panda. Print Wrong password. after each wrong attempt. The last line is Welcome or Account locked.

With the replies tiger then lion then panda, the program prints the lines below. Your program must print exactly these lines.

Example run

Wrong password.
Wrong password.
Welcome

Write code · Medium

Powers of two. Print every power of 2 that is below one million, on one line, and then how many there were.

Print the powers first, starting with 1, then how many there were.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288
How many: 20

Write code · Hard

Greatest common divisor. The largest number that divides two whole numbers exactly can be found with a method that is over 2000 years old, Euclid's algorithm: as long as the second number is not zero, replace the pair (first, second) with (second, first % second). When the second number is zero, the first is the answer. Ask for two positive whole numbers and print their greatest common divisor. Test with 48 and 18, which should give 6.

With the replies 48 then 18, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Greatest common divisor: 6

Write code · Hard

Is it a palindrome number?. Ask for a positive whole number and print whether it reads the same backwards, such as 12321, by reversing it with arithmetic (no strings).

Print True when the number reads the same backwards and False when it does not.

With the reply 12321, the program prints the lines below. Your program must print exactly these lines.

Example run

True

Write code · Hard

A calculator that keeps going. Take the command calculator from Chapter 12 and put it in a loop, so that it handles one command after another until the user types quit. Support at least add, sub, mul and div. A command that cannot be understood, including one with something that is not a number, should print a message and not end the program. Print how many calculations were done at the end.

Print each result on its own line. Your messages should not contain digits. Print the number of calculations last.

With the replies mul 6 7 then sub 10 4 then fly then div 1 0 then mul 2 two then quit, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

42.0
6.0
Commands: add, sub, mul, div (two numbers), quit
Cannot divide by zero.
Those are not both numbers.
Goodbye. Calculations done: 2

Chapter project: Savings goal

Project

Save up for a goal. Write a program that follows deposits until a savings goal is reached. All amounts are whole dollars.

  1. Ask for the goal. Keep asking until the reply is a whole number above zero. For every other reply, print Please type a whole number above zero.
  2. Then ask for deposits, one per pass, as long as the money saved is below the goal.
    • The reply stop ends the loop early.
    • A reply that is not made of digits only, or the reply 0, prints Not counted. and the loop goes round again.
    • A good deposit is added to the money saved, and the program prints a line in this form: Saved 35 of 50
  3. After the loop, print the number of good deposits in this form: Deposits: 2
  4. The last line is Goal reached! when the money saved is equal to the goal or above it. If not, it has this form: Still needed: 15

Plan before you write: which loop is "ask until valid", and which one has two ways to end?

With the replies ten then -5 then 30 then 10 then lots then 0 then 25, the program prints the lines below. Your program must print exactly these lines.

Example run

Please type a whole number above zero.
Please type a whole number above zero.
Saved 10 of 30
Not counted.
Not counted.
Saved 35 of 30
Deposits: 2
Goal reached!