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 lessonThis 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 digitsDon'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
- Countdown TimerBeginner
- Power of 2 FinderBeginner
- Predict the OutputBeginner
- The Collatz SequenceBeginner
All Python exercises · 50 practice problems · Control Flow quiz