Python 3D Academyবাংলা

while loops

🌍 In real life. You fill a bucket with a mug: pour a mug, look at the bucket, and if it isn't full yet, pour another. You don't decide in advance how many mugs it takes; you check before every mug and stop as soon as it's full.

That "check, do, check again" pattern is a loop, and while is Python's way to write it.

The idea in one sentence: while repeats its block as long as its condition is True, checking the condition again before every lap.

Its words:

  • loop: code that runs again and again
  • lap (or iteration): one run through the loop's block
  • loop variable: the variable the condition depends on, which the block changes
  • infinite loop: a loop whose condition never becomes False, so it never stops

Step by step, for while count <= 3: with count starting at 1:

  1. Check: 1 <= 3 is True, so run the block: print 1, then count becomes 2.
  2. Back to the top. Check 2 <= 3: True, so print 2; count becomes 3.
  3. Check 3 <= 3: True, so print 3; count becomes 4.
  4. Check 4 <= 3: False, so the loop ends, and Python carries on below it.
count = 1
while count <= 3:
    print(count)
    count += 1
print("Done!")
When count reaches 4, the condition is False, so the loop stops and Python carries on below it.

How Python does it. The condition is checked only at the top of each lap, never in the middle of the block. So the block always finishes its lap, even if the condition became False halfway through. If the condition is False the very first time, the block never runs at all.

Something inside the block must change the loop variable; otherwise the condition never becomes False. A loop can also count down:

n = int(input("Start from: "))
while n > 0:
    print(n)
    n -= 1
print("Liftoff!")

while is the right loop when you don't know in advance how many laps you need, like doubling a number until it gets big enough:

money = 1
days = 0
while money < 100:
    money = money * 2
    days += 1
print(days, "days to reach", money)

What it costs. A loop's block runs once per lap, so the number of laps is the work. Counting from 1 up to n takes n laps: a million laps for n = 1,000,000. The doubling loop above is far quicker: money goes 1, 2, 4, 8, … and passes 100 after only 7 laps. To pass a million it would need just 20 laps, because each lap doubles it.

Mistakes and edge cases.

  • Forgetting to change the variable. Without count += 1, count <= 3 stays True forever: an infinite loop. Press ⏹ Stop to end it.
  • The change outside the block. count += 1 written without its indent runs only after the loop, so the loop never ends.
  • < or <=. while count < 3: runs 2 laps from 1, not 3. Check the last lap by hand.
  • A loop that never starts. If the condition is False at the start, the block is skipped and there's no error.
  • The variable doesn't exist yet. while count <= 3: before count = 1 gives NameError: name 'count' is not defined.

Quiz

  1. What does this print?

    n = 3
    while n > 0:
        print(n)
        n -= 1
  2. What does this print?

    x = 1
    while x < 20:
        x = x * 2
    print(x)
  3. What does this print?

    i = 5
    while i < 3:
        print("hi")
    print("end")
  4. What happens if you forget count += 1 in a while count <= 3: loop?

    • The loop never stops, because count stays the same
    • Python adds 1 for you
    • The loop runs exactly 3 times
  5. Which line has a mistake?

    count = 0
    while count < 3
        print(count)
        count += 1

Coding tasks

  1. Ask for a whole number n. Print the numbers from 1 to n, one per line.

  2. Ask for a whole number. Count down from it to 1, one number per line, then print Go!. If the number is 0, just print Go!.

  3. Ask for a whole number n (1 or more). Start with 1 and keep doubling it while it is smaller than n. Print the number you end up with: the first of 1, 2, 4, 8, 16, … that is at least n.