Editor

Fix the Bug: Digit Counter

Beginner · Fix the bug · from Python While Loops: When For Loops Aren't Enough

From the lesson: Python While Loops: When For Loops Aren't Enough

A vending machine doesn't know how many coins you'll insert. It just keeps waiting: "while the total is less than the price, keep accepting coins." It can't use a for loop because it doesn't know the number of iterations in advance. It needs a while loop.

Read the lesson

This code is supposed to count how many digits are in a number by repeatedly dividing by 10. But it has a bug - it gives the wrong answer for the number 9999. Fix the code so it prints:

9999 has 4 digits

Don't change the number or the final print statement.

number = 9999
original = number
digits = 0
while number >= 10:
number = number // 10
digits += 1
print(f"{original} has {digits} digits")

More While Loops exercises

All Python exercises · 50 practice problems · Control Flow quiz